旋轉數組的尋找-經典

來源:互聯網
上載者:User

標籤: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;}

 

旋轉數組的尋找-經典

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.