Search Insert Position(Easy,二分搜索)
题目描述:
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.
样例:
[1,3,5,6]
, 5 → 2
[1,3,5,6]
, 2 → 1
[1,3,5,6]
, 7 → 4
[1,3,5,6]
, 0 → 0
时间复杂度:
O(log(n))
Code:
1 int searchInsert(vector<int> &A, int target) { 2 // write your code here 3 long long first = 0; 4 long long nums = A.size(); 5 long long last = nums - 1; 6 long long mid; 7 while(first <= last){ 8 mid = first + ((last - first + 1)>>1); 9 if(A[mid] == target) return mid; 10 else if((first == last) && (A[mid] > target)) // 如果没有找到,目标较小,插在mid上 11 return mid; 12 else if((first == last) && (A[mid] < target)) 13 return mid +1; // 如果没有找到,目标较大,插在mid+1上 14 else if(A[mid] > target) last = mid -1; 15 else first = mid + 1; 16 } 17 }