[LeetCode95]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.

Analysis:

重复元素的确会影响A[m]>=A[l] 判断递增序列,比如[1,4,5,1,1,1,1]

如果A[m]>=A[l]不能确定递增,那就把它拆分成两个条件
1. A[m]>A[l] 递增
2. A[m] ==A[l] 确定不了,那就l++,往下看一步即可。

Java

int l = 0;
		int r = A.length-1;
		while(l<=r){
			int m = (l+r)/2;
			if(A[m]==target) return true;
			if(A[m]>A[l]){
				if(A[l]<=target && A[m]>target){
					r = m-1;
				}else
					l = m+1;
			}else if(A[m]<A[l]){
				if(A[m]<target && target<=A[r])
					l = m+1;
				else
					r = m-1;
			}else {
				l++;
			}
		}
		return false;

c++

bool search(int A[], int n, int target) {
        int start = 0;
        int end = n-1;
        while(start <= end){
            int mid = (start + end)/2;
            if(A[mid] == target) return true;
            if(A[mid] > A[start]){
                if(target <= A[mid] && target >= A[start]) end = mid-1;
                else start = mid+1;
            }else if(A[mid]< A[start]){
                if(target >= A[start] || target < A[mid]) end = mid-1;
                else start = mid+1;
            }else{
                start++;
            }
            
        }
        return false;
    }




你可能感兴趣的:(LeetCode,search,binary)