Skip to content

[LeetCode] 35. 搜索插入位置 #79

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

Open
Animenzzzz opened this issue Sep 6, 2019 · 0 comments
Open

[LeetCode] 35. 搜索插入位置 #79

Animenzzzz opened this issue Sep 6, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

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

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

示例 1:

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

示例 2:

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

示例 3:

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

示例 4:

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

解题思路:题目比较简单,分情况,若比第一个数还小,返回0;若等于下标,返回下标;若遍历到了最后一个数,则返回最后一个数下标+1;若比当前数大,且小于其后一个数,返回当前下标+1

C++解题:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        if(nums[0] > target) return 0;
        for (int i = 0; i < nums.size(); i++)
        {
            if(nums[i] == target) return i;
            if(i == nums.size() - 1) return nums.size();
            if(nums[i] < target && nums[i + 1] > target) return i+1;
        }
        return 0;
    }
};
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