Search Insert Position 查找給定元素在數組中的位置,若沒有則返回應該在的位置

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 → 0spa

如題所述,最直觀的作法就是二分查找。不過在使用二分查找解決此問題時,須要多加當心,先考慮清楚全部狀況,再開始編碼。code

首先考慮邊界:blog

  1. 若給定target小於數組第一個元素,返回0;
  2. 若target大於最後一個元素,返回n

使用二分,結束循環條件應該是high-low=1的狀況。get

例如[1,3,5,6]中查找2,二分一次後,low=0,high=1,此時A[low]=1,A[high]=3。it

若按照日常使用的二分查找就應該找不到元素exit了,可是要返回元素的值則須要再進一步處理,此時low+1,或high-1即爲元素應該的位置。io

下面代碼裏我把target等於邊界值(數組第1個和第n個)的狀況放到最後比較了。class

 1 class Solution {
 2 public:
 3     int searchInsert(int A[], int n, int target) {
 4         if(A == NULL || n < 1)
 5             return -1;
 6         if(target < A[0])
 7             return 0;
 8         if(target > A[n-1])
 9             return n;
10         
11         int low = 0;
12         int high = n-1;
13         
14         int mid = 0;
15         
16         while(high-low>1){
17             mid = low + (high - low)/2;
18             if(A[mid] == target)
19                 return mid;
20             else if(A[mid] > target)
21                 high = mid;
22             else
23                 low = mid;
24         }
25         
26         if(high-low ==1)
27             if(A[low] == target)
28                 return low;
29             if(A[high] == target)
30                 return high;
31             else
32                 return low+1;
33                 
34     }
35 };
相關文章
相關標籤/搜索