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 二分查找
C++(6ms):
1 class Solution { 2 public: 3 int searchInsert(vector & nums, int target) { 4 int left = 0 ; 5 int right = nums.size()-1 ; 6 while(left <= right){ 7 int mid = left + (right - left)/2 ; 8 if (target == nums[mid]) 9 return mid ;10 else if(target > nums[mid])11 left = mid + 1; 12 else13 right = mid - 1;14 }15 return left ;16 }17 };