LeetCode每日一题: 搜索插入位置(No.35)

栏目: 编程工具 · 发布时间: 6年前

给定一个 排序 数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
复制代码

示例:

输入: [1,3,5,6], 5
输出: 2

输入: [1,3,5,6], 2
输出: 1

输入: [1,3,5,6], 7
输出: 4

输入: [1,3,5,6], 0
输出: 0
复制代码

思考:

因为数排序数组,所以循环数组元素找到与目标值相等或者第一个大于目标值的元素,返回其数组下标即可。
复制代码

实现:

class Solution {
    public int searchInsert(int[] nums, int target) {
        for (int count = 0; count < nums.length; count++) {
            if (nums[count] == target||nums[count] > target) {
                return count;
            }
        }
        return nums.length;
    }
}复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Linux Command Line

The Linux Command Line

William E. Shotts Jr. / No Starch Press, Incorporated / 2012-1-17 / USD 39.95

You've experienced the shiny, point-and-click surface of your Linux computer-now dive below and explore its depths with the power of the command line. The Linux Command Line takes you from your very ......一起来看看 《The Linux Command Line》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具