Search in Rotated Sorted Array II, Leetcode 解题笔记

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.

跟之前的区别在于多出现了一种情况,即A[left] == A[mid]的情况,如:
[1, 3, 1, 1, 1]
如果是这种情况,则只需left++比较下一个元素。

public class Solution {
    public boolean search(int[] A, int target) {
        int left = 0;
        int right = A.length-1;
         
        while(left <= right){
            int mid = (right + left)/2;
            if(A[mid] == target){
                return true;
            }
            if(A[mid] > A[left]){
                if(A[left] <= target && target < A[mid]){
                    right = mid-1;
                }
                else{
                    left = mid+1;
                }
            }
            else if(A[mid] < A[left]){
                if(A[mid] < target && target <= A[right]){
                    left = mid+1;
                }
                else{
                    right = mid-1;
                }
            }
            else{
                left++;
            }
        }
        return false;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s