標籤:count public target 複雜 二分尋找 https value 思路 mina
https://leetcode.com/problems/search-in-rotated-sorted-array/?tab=Description
很好的很經典的題目。今天複習了一下。之前的思路雖然有了,但是對於相等的數位處理很複雜,容易出錯。今天看到了一個很好的解法。
https://discuss.leetcode.com/topic/3538/concise-o-log-n-binary-search-solution
思路是先找出最小的數位下標,通過 mid > hi,就low = mid+1,否則 hi=mid,來找出。
然後二分尋找的時候,用的是位移過的實際下標。
整體代碼:
class Solution {public: int search(int A[], int n, int target) { int lo=0,hi=n-1; // find the index of the smallest value using binary search. // Loop will terminate since mid < hi, and lo or hi will shrink by at least 1. // Proof by contradiction that mid < hi: if mid==hi, then lo==hi and loop would have been terminated. while(lo<hi){ int mid=(lo+hi)/2; if(A[mid]>A[hi]) lo=mid+1; else hi=mid; } // lo==hi is the index of the smallest value and also the number of places rotated. int rot=lo; lo=0;hi=n-1; // The usual binary search and accounting for rotation. while(lo<=hi){ int mid=(lo+hi)/2; int realmid=(mid+rot)%n; if(A[realmid]==target)return realmid; if(A[realmid]<target)lo=mid+1; else hi=mid-1; } return -1; }};
當然了,還有常規的做法,就是這樣的。
考慮問題的時候,也不要太過複雜化了。
public int search(int[] A, int target) { int lo = 0; int hi = A.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (A[mid] == target) return mid; if (A[lo] <= A[mid]) { if (target >= A[lo] && target < A[mid]) { hi = mid - 1; } else { lo = mid + 1; } } else { if (target > A[mid] && target <= A[hi]) { lo = mid + 1; } else { hi = mid - 1; } } } return A[lo] == target ? lo : -1;}
旋轉數組的尋找-經典