Search in Rotated Sorted Array II

Search in Rotated Sorted Array II_第1张图片
Search in Rotated Sorted Array II.png

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

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

===================== C++ 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 &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;
}

};

你可能感兴趣的:(Search in Rotated Sorted Array II)