35. 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.spa

You may assume no duplicates in the array.code

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 → 0blog

基本都是用二分法吧,只是在while循环前先将边界状况考虑,while循环的结束条件是left<right-1,这样当最后一轮循环后left=mid,right=left+1;get

若mid==target,返回mid;不然返回right。(若right==target正好,若right<target,则right即为target将要插入的位置)it

代码:io

 1 class Solution {
 2 public:
 3 int searchInsert(vector<int>& nums, int target)
 4 {
 5     int size=nums.size();
 6     if (size==0)
 7     {
 8         return 0;
 9     }
10     if (nums[0]>=target)
11     {
12         return 0;
13     }
14     if (nums[size-1]<target)
15     {
16         return size;
17     }
18     int left=0,right=size-1;
19     while(left<right-1)
20     {
21         int mid=(left+right)>>1;
22         if (nums[mid]==target)
23         {
24             return mid;
25         } 
26         else if(nums[mid]>target)
27         {
28             right=mid;
29         }
30         else
31             left=mid;
32     }
33     return right;
34 }
35 };
相关文章
相关标签/搜索