81. Search in Rotated Sorted Array II

来源:互联网 发布:vb log无法识别 编辑:程序博客网 时间:2024/06/06 05:57

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Write a function to determine if a given target is in the array.

The array may contain duplicates.

首先说一下该题的上一题的思路:寻找最小值对应坐标  确定查找区间  找到最终结果

但是该题中存在重复值,有重复值将会产生一个问题就是我们在二分时候只能确定部分有序,因此我们的解决方案也基于此,代码如下:

public boolean search(int[] nums, int target) {
       int left = 0, right = nums.length - 1;
       while(left < right){
           int mid = (left + right) / 2;
           if(nums[mid] == target){
               return true;
           }else if(nums[mid] > nums[left]){  // from left to mid is sorted
               if(target >= nums[left] && target < nums[mid]){
                   right = mid - 1;
               }else{
                   left = mid + 1;
               }
           }else if(nums[mid] < nums[left]){ // from mid to right is sorted
               if(target > nums[mid] && target <= nums[right]){
                   left = mid + 1;
               }else{
                   right = mid - 1;
               }
           }else{
               left++;
           }
       }
       if(nums[left] == target){
           return true;
       }else{
           return false;
       }
    }
}

0 0
原创粉丝点击