題目:
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
題解:
這道題與之前Search in Rotated Sorted Array類似,問題只在於存在dupilcate。那麼和之前那道題的解法區別就是,不能通過比較A[mid]和邊緣值來確定哪邊是有序的,會出現A[mid]與邊緣值相等的狀態。所以,解決方法就是對於A[mid]==A[low]和A[mid]==A[high]單獨處理。
當中間值與邊緣值相等時,讓指向邊緣值的指標分別往前移動,忽略掉這個相同點,再用之前的方法判斷即可。
這一改變增加了時間複雜度,試想一個陣列有同一數字組成{1,1,1,1,1},target=2, 那麼這個演算法就會將整個陣列遍歷,時間複雜度由O(logn)升到O(n)
實現程式碼如下:
1 public boolean search(int [] A,int target){
2 if(A==null||A.length==0)
3 return false;
4
5 int low = 0;
6 int high = A.length-1;
7
8 while(low <= high){
9 int mid = (low + high)/2;
10 if(target < A[mid]){
11 if(A[mid]<A[high])//right side is sorted
12 high = mid - 1;//target must in left side
13 else if(A[mid]==A[high])//cannot tell right is sorted, move pointer high
14 high--;
15 else//left side is sorted
16 if(target<A[low])
17 low = mid + 1;
18 else
19 high = mid - 1;
20 }else if(target > A[mid]){
21 if(A[low]<A[mid])//left side is sorted
22 low = mid + 1;//target must in right side
23 else if(A[low]==A[mid])//cannot tell left is sorted, move pointer low
24 low++;
25 else//right side is sorted
26 if(target>A[high])
27 high = mid - 1;
28 else
29 low = mid + 1;
30 }else
31 return true;
32 }
33
34 return false;
35 }
2 if(A==null||A.length==0)
3 return false;
4
5 int low = 0;
6 int high = A.length-1;
7
8 while(low <= high){
9 int mid = (low + high)/2;
10 if(target < A[mid]){
11 if(A[mid]<A[high])//right side is sorted
12 high = mid - 1;//target must in left side
13 else if(A[mid]==A[high])//cannot tell right is sorted, move pointer high
14 high--;
15 else//left side is sorted
16 if(target<A[low])
17 low = mid + 1;
18 else
19 high = mid - 1;
20 }else if(target > A[mid]){
21 if(A[low]<A[mid])//left side is sorted
22 low = mid + 1;//target must in right side
23 else if(A[low]==A[mid])//cannot tell left is sorted, move pointer low
24 low++;
25 else//right side is sorted
26 if(target>A[high])
27 high = mid - 1;
28 else
29 low = mid + 1;
30 }else
31 return true;
32 }
33
34 return false;
35 }