Search Insert Position--LeetCode

来源:互联网 发布:知乎PLUS 编辑:程序博客网 时间:2024/06/04 17:57

1.题目

Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

2.题意

给定已排序的数组和目标值,如果找到目标值,则返回它的下标。如果找不到, 返回它应被插入的位置。假定数组中没有重复项。

3.分析

1)遍历数组,若nums[i]>=target,则返回i
如果target比nums中任何数都大,则返回数组长度
注意不要把return nums.size();写成别的数字

2)二分查找,时间复杂度是O(logn),空间复杂度是O(1)
如果数组中不存在target
left一定停在恰好比target大的index上
right一定停在恰好比target小的index上

4.代码

1)

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

2)

class Solution {public:    int searchInsert(vector<int>& nums, int target) {        int len = nums.size();        if(len == 0)            return 0;        if(target <= nums[0])            return 0;        if(target > nums[len - 1])            return len;        int left = 0;        int right = nums.size() - 1;        while(left <= right)        {            int mid = left + (right - left) / 2;            if(nums[mid] == target)                return mid;            else if(target < nums[mid])                right = mid - 1;            else                left = mid + 1;        }        return left;    }};
原创粉丝点击