码迷,mamicode.com
首页 > 其他好文 > 详细

Jan 23 - Search In Rotated Array II; Array; Binary Search;

时间:2016-01-24 07:02:47      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

Jan 23 - Search In Rotated Array II; Array; Binary Search;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5154511.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!