美文网首页
Search in Rotated Sorted Array I

Search in Rotated Sorted Array I

作者: 一枚煎餅 | 来源:发表于2016-09-15 14:20 被阅读0次
    Search in Rotated Sorted Array II.png

    ===================== 解題思路 =====================

    基本跟第一題差不多 但是這次 A[mid] 不是跟 A[0] 比較而是跟 A[left] 主要因為遇到相同的狀況 A[mid] = A[left] 時 要把 left 往右移動一格 其餘就是一樣了

    ===================== C++ code ====================

    <pre><code>
    class Solution {

    /** 
     * param A : an integer ratated sorted array and duplicates are allowed
     * param target :  an integer to be search
     * return : a boolean 
     */
    

    public:

    bool search(vector<int> &A, int target) {
        // write your code here
        if(A.size() == 0) return false;
        int left = 0, right = A.size() -1;
        while(left + 1 < right)
        {
            int mid = (left + right) / 2;
            if(A[mid] == target) return true;
            if(A[mid] > A[left])
            {
                if(A[left] <= target && target <= A[mid])
                {
                    right = mid;
                }
                else left = mid;
            }
            else if(A[mid] < A[left])
            {
                if(A[mid] < target && target < A[A.size() - 1])
                {
                    left = mid;
                }
                else right = mid;
            }
            else
            {
                left++;
            }
        }
        if(A[left] == target || A[right] == target) return true;
        return false;
    }
    

    };
    <code><pre>

    相关文章

      网友评论

          本文标题:Search in Rotated Sorted Array I

          本文链接:https://www.haomeiwen.com/subject/eesbettx.html