Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

35、 搜索插入位置 #53

Open
hubvue opened this issue Jan 12, 2020 · 0 comments
Open

35、 搜索插入位置 #53

hubvue opened this issue Jan 12, 2020 · 0 comments

Comments

@hubvue
Copy link
Owner

hubvue commented Jan 12, 2020

题目

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

示例 1:

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

示例 2:

输入: [1,3,5,6], 2
输出: 1
```txt
示例 3:
```txt
输入: [1,3,5,6], 7
输出: 4

示例 4:

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

题解

解题思路

很简单的一道题,直接遍历数组即可,当找到目标值的时候,返回其索引。没找到的时候:当寻找到第一个大于目标值的时候插入位置在此值的位置,如果找到最后还没有找到即插入位置在最后。

代码

var searchInsert = function(nums, target) {
    let len = nums.length;
    for(let i = 0; i < len; i ++) {
        if(target === nums[i]) {
            return i;
        }
        if(target < nums[i]){
            return i;
        }
        if(i == len - 1) {
            return len;
        }
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant