LeetCode | 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.

思路:

类似
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);
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17336653
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞