描述: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
思路1:直观的想法,遍历数组,一旦当前元素>=target,当前元素的位置即为插入位置,边界问题处理一下即可。时间复杂度:O(n)
1 class Solution { 2 public: 3 int searchInsert(int A[], int n, int target) { 4 5 if(target > A[n-1]) 6 return n; 7 8 else { 9 for(int i = 0; i < n; i++) { 10 if(A[i] >= target) 11 return i; 12 } 13 } 14 } 15 };
思路2:由于给定数组为已经排好序的,可以使用二分查找,比较A[mid]与target的大小。时间复杂度:O(logn)
1 class Solution { 2 public: 3 int searchInsert(int A[], int n, int target) { 4 5 int start = 0; 6 int end = n - 1; 7 int mid = 0; 8 9 while(end >= start) { 10 11 mid = (start + end) / 2; 12 if(target == A[mid]) 13 return mid; 14 else if(target > A[mid]) 15 start = mid + 1; 16 else 17 end = mid - 1; 18 } 19 20 if(target > A[mid]) 21 return mid + 1; 22 else 23 return mid; 24 25 } 26 };