描述: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.spa
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 code
思路1:直觀的想法,遍歷數組,一旦當前元素>=target,當前元素的位置即爲插入位置,邊界問題處理一下便可。時間複雜度:O(n)blog
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)get
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 };