public class Solution {
    public boolean search(int[] nums, int target) {
        int len = nums.length;
        if(len == 0) return false;
        int low = 0;
        int high = len-1;
        while(low < high){
            int mid = (low+high)/2; // do not concern the integer overrange situation
            if(nums[mid] == target) return true;
            if(nums[mid] < nums[high] || nums[mid] < nums[low]){
                if(target > nums[mid] && target <= nums[high]) low = mid + 1;
                else high = mid - 1;
            }
            else if(nums[mid] > nums[low] || nums[mid] > nums[high]){
                if(target < nums[mid] && target >= nums[low]) high = mid - 1;
                else low = mid + 1;
            }
            else high--;
        }
        if(nums[low] == target) return true;
        return false;
}
}

 

Initially low = 0, high = len-1; the condition of while loop is low < high; mid = (low+high)/2;

if nums[mid] == target, sure we find the value same as the target, return true. If not, 

We analyze three cases:

1. right part from mid to high sorted, and left part from low to mid unsorted. (nums[mid] < nums[high] || nums[mid] < nums[low])

  Then we compare the target with some specific value to detemine which part the target should be in if its in the array.

   if(target > nums[mid] && target <= nums[high]) target should be in the right part, set low = mid +1;

   otherwise the target should be in the left part, high = mid - 1;

2. left part is sorted. (nums[mid] > nums[low] || nums[mid] > nums[high])

  Similarly, if(target< nums[mid] && target >= nums[low]) high = mid -1;

otherwise, the target should be in the right part, low = mid + 1;

3. The last possibility is that nums[low] == nums[mid] == nums[high], in this case, just let high--; to reduce the duplication occurance.

 

posted on 2016-01-24 06:40  爱推理的骑士  阅读(120)  评论(0编辑  收藏  举报