81. 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?
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Write a function to determine if a given target is in the array.
The array may contain duplicates.

Solution:

思路: 和33题:http://www.jianshu.com/p/997dd993f5bd思路是相同的,不同的是因为可能会有duplicates,这样一来在判断rotated的部分的时候就会出现问题,比如like 4444444441234, or 456744444444。所以需要做的是让lo跳过duplicates就可以,这样就可以和33题一样继续可以处理。题目只需要判断bool是否含有target,因为除了lo跳过的duplicates还在mid处还有,所以OK
Time Complexity: Avg O(logN)
worst case是 O(n),比如1111121111中target是2
Space Complexity: O(1)

Solution Code:

class Solution {
    public boolean search(int[] A, int target) {
        if(A == null || A.length == 0) return false;
        
        int lo = 0, hi = A.length - 1;
        while (lo <= hi) {
            int mid = (lo + hi) / 2;
            if (A[mid] == target) return true;

            if (A[mid] > A[lo]) {
                // rotated part is in the right
                if (target >= A[lo] && target < A[mid]) {
                    // target is in the left
                    hi = mid - 1;
                } else {
                    // target is in the right
                    lo = mid + 1;
                }
            } else if(A[mid] < A[lo]) {
                // rotated part is on the left
                if (target > A[mid] && target <= A[hi]) {
                    // target is in the right
                    lo = mid + 1;
                } else {
                    // target is in the left
                    hi = mid - 1;
                }
            }
            else {
                // like 4444444441234, or 456744444444. In these cases,
                // we can't know where the rorated part is, so we let lo skip the repeated one 
                // because we only need to find one (mid still has)
                lo++;
            }
        }
        return false;
    }
}

你可能感兴趣的:(81. Search in Rotated Sorted Array II)