Search in Rotated Sorted Array II

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.

思路:

  二分查找

我的代码:

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

别人代码:

    public boolean search(int[] A, int target) {
        if (A == null || A.length == 0) {
            return false;
        }
        
        int l = 0;
        int r = A.length - 1;
        
        while (l <= r) {
            int mid = l + (r - l) / 2;
            
            if (A[mid] == target) {
                return true;
            }
            
            // left sort
            if (A[mid] > A[l]) {
                // out of range.
                if (target > A[mid] || target < A[l]) {
                    l = mid + 1;
                } else {
                    r = mid - 1;
                }
            // right sort.    
            } else if (A[mid] < A[l]) {
                // out of range.
                if (target < A[mid] || target > A[r]) {
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            } else {
                // move one node.
                l++;
            }
        }
        
        return false;
    }
View Code

学习之处:

  • 此题和Search in Rotated Sorted Array有不同之处,题1 A[left] <= A[mid] 即可判断是Left-->mid是升序的,但在题2中,A[left]<=A[mid]有可能是这样的11211,所以需要分开A[left] < A[mid] left -->mid必定是升序的,对于A[left] == A[mid]的情况需要left++ 进一步判断 
  • 有没有duplicates 区别在于,当A[left] < A[right]的时候可以肯定判断left-->right是上升的,A[left]==A[right]的时候,不可以判断,因为有可能出现上升又下降的情况。紧急此条即可。

posted on 2015-03-08 15:21  zhouzhou0615  阅读(147)  评论(0编辑  收藏  举报

导航