leetcode -- Search in Rotated Sorted Array I &II 重点可以考

https://leetcode.com/problems/search-in-rotated-sorted-array/
https://leetcode.com/problems/search-in-rotated-sorted-array-ii/

暂时先只了解思路就行。就是BS, 二分的变种。

只是这里边界条件不好确定,可以分的情况太多。复习的时候再写一下。
我们要参考http://blog.allenzhao.com/leetcode/2014/09/16/LeetCode-Search-in-Rotated-Sorted-Array/这里的图, 那张图用将搜索区间按break point分成了M1,M2,我们只需要每次搜索的时候drop掉M1或者M2就行了。

没有duplicate

class Solution:
    # @param A, a list of integers
    # @param target, an integer to be searched
    # @return an integer
    def search(self, A, target):
        left = 0; right = len(A) - 1
        while left <= right:
            mid = (left + right) / 2
            if target == A[mid]:
                return mid
            if A[mid] >= A[left]:#在左段M1,进行bs
                if target < A[mid] and target >= A[left]:
                    right = mid - 1
                else:
                    left = mid + 1
            elif A[mid] < A[right]:#在右段M2,进行bs
                if target > A[mid] and target <= A[right]:
                    left = mid + 1
                else:
                    right = mid - 1
        return -1

有duplicate

class Solution:
    # @param A a list of integers
    # @param target an integer
    # @return a boolean
    def search(self, A, target):
        left=0; right=len(A)-1
        while left<=right:
            mid=(left+right)/2
            if A[mid]==target: return True
            if A[left]==A[mid]==A[right]:#重复的话,就不知道drop哪个了
                left+=1; right-=1
            elif A[left]<=A[mid]:#在M1, drop M2
                if A[left]<=target<A[mid]: right=mid-1
                else: left=mid+1
            else:#在M2, drop M1
                if A[mid]<=target<A[left]: left=mid+1
                else:right=mid-1
        return False

参考:
http://www.cnblogs.com/zuoyuan/p/3777422.html
http://www.cnblogs.com/zuoyuan/p/3783671.html
http://bangbingsyb.blogspot.hk/2014/11/leetcode-search-in-rotated-sorted-array.html

http://blog.allenzhao.com/leetcode/2014/09/16/LeetCode-Search-in-Rotated-Sorted-Array/
http://blog.allenzhao.com/leetcode/2014/09/17/LeetCode-Search-in-Rotated-Sorted-Array-II/

这里面有interview的时候,问这种问题的套路
http://rleetcode.blogspot.hk/2014/03/search-in-rotated-sorted-array.html

你可能感兴趣的:(LeetCode)