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.

 

class Solution {
public:
    bool help(int *a,int from,int to,int x) {
        if (from > to) {
            return false;
        }
        if (to - from <= 1) {
            return (a[from] == x) || (a[to] == x);
        }
      
        int mid = (from + to) >> 1;
        if (a[mid] == x) {
            return true;
        }
        if ((a[mid] > a[from]) || (a[mid] > a[to])) {
            return ((x < a[mid]) && (x >= a[from]))?help(a, from, mid - 1, x):help(a, mid + 1, to ,x);
        }
        if ((a[mid] < a[from]) || (a[mid] < a[to])) {
            return ((x > a[mid]) && (x <= a[to]))?help(a, mid + 1,to,x):help(a,from,mid - 1, x);
        }
        return help(a, from + 1, mid - 1,x) || help(a, mid + 1, to - 1, x);
      
        

    }
    bool search(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return help(A, 0, n - 1, target);
        
    }
};

 

posted @ 2013-09-15 15:35  一只会思考的猪  阅读(166)  评论(0编辑  收藏  举报