Leetcode: 81. Search in Rotated Sorted Array II

Description

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.

思路

  • 肯定是个二分
  • 因为是个旋转数组,前一部分比后一部分都大
  • 所以判断中点是落到前一半还是后一半了,若是前一半,然后根据target和mid,low的关系可以给出二分判断
  • 因为数组可以重复,若是mid == low, 则low++,因为此时无法判断去掉哪一边

代码

class Solution {
public:
    bool search(vector<int>& nums, int target) {
        int len = nums.size();
        if(len == 0) return false;
        
        int low = 0, high = len - 1, mid = 0;
        while(low < high){
            mid = low + (high - low) / 2;
            if(nums[mid] == target)
                return true;
            
            if(nums[mid] > nums[low]){
                if(nums[mid] < target || nums[low] > target)
                    low = mid + 1;
                else high = mid - 1;
            }
            else if(nums[mid] < nums[low]){
                if(target >= nums[low] || target < nums[mid])
                    high = mid - 1;
                else low = mid + 1;
            }
            else low++;
        }
        
        return target == nums[low];
    }
};
posted @ 2017-06-05 15:20  JeffLai  阅读(176)  评论(0编辑  收藏  举报