Search in rotated sorted array ii

题目:

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.

思路:此题比较复杂,有三种情况需要判断:1. 左区间是正常的。 2. 右区间正常。 3. 左边和中间相等, 则说明左边到中间都是相同数字,此时需要判断时候和右边相等,如果不相等则搜索右边,如果相等则需要搜索两边。

代码:

class Solution {
public:
    bool search(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int left = 0;
        int right = n-1;
        
        
        while (left<=right){
            
            int mid = (left+right)/2;
            
            if (A[mid] == target) return true;
            
            if (A[left]<A[mid]){//left is normally ordered
                
                if (A[left]<=target && target<=A[mid]) right = mid-1;
                else left = mid+1;
            }
            
            else if (A[mid]<A[left]){//right is normally ordered
                
                if (A[mid]<=target && target<=A[right]) left = mid+1;
                else right = mid -1;
            }
            
            else if (A[left] == A[mid]){//left half is all repeats
            
                    if (A[mid] != A[right]) //If right is diff search it
                       left = mid+1;
                    else{//Else, we have to search both halves
                        
                        int result = search(A+left, mid-left, target);//search left
                        if (result == false) 
                            return search(A+mid, right-mid, target);//search right
                        else return result;
                    }
            }
        }
        
        return false;
    }
};

  

原文地址:https://www.cnblogs.com/tanghulu321/p/3055784.html