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 };