LeetCode | Search in Rotated Sorted Array II

来源:互联网 发布:mindmanager mac破解版 编辑:程序博客网 时间:2024/05/16 17:53

题目:

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.


思路:

类似http://blog.csdn.net/lanxu_yy/article/details/17336451。但是遇到两个相等的数时要特殊考虑,最坏情况下,左侧和右侧的数组都需要遍历。

代码:

class Solution {public:    bool search(int A[], int n, int target) {        return searchInternal(A, 0, n-1, target);    }        bool searchInternal(int A[], int begin, int end, int target){        if(begin + 1 == end || begin == end){            return A[begin] == target || A[end] == target;        }                int middle = begin + (end - begin) / 2;                if(A[begin] < A[middle]){            if(A[begin] <= target && target <= A[middle]){                return searchInternal(A, begin, middle, target);            }            else{                return searchInternal(A, middle, end, target);            }        }        else if(A[middle] < A[end]){            if(A[middle] <= target && target <= A[end]){                return searchInternal(A, middle, end, target);            }            else{                return searchInternal(A, begin, middle, target);            }        }        else{            return searchInternal(A, begin, middle, target) || searchInternal(A, middle, end, target);        }    }};


0 0
原创粉丝点击