81. Search in Rotated Sorted Array II

问题描述:

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

(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false

Follow up:

  • This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
  • Would this affect the run-time complexity? How and why?

 

解题思路:

这道题是leetcode33. Search in rotated sorted array的follow up

我认为依然可以用二分搜索来检查,但是因为重复值出现的原因,会出现nums[mid] = nums[right]的情况

一开始我认为如果这种情况出现,那么说明右半边是一样的值,直到我看到了这个test case: [1,1,1,3,1]

符合题意,但是不符合我的假设:)

所以应该把right向左移一位

 

代码:

class Solution {
public:
    bool search(vector<int>& nums, int target) {
        if(nums.size() == 0)
            return false;
        int left = 0;
        int right = nums.size() - 1;
        while(left <= right){
            int mid = left + (right - left)/2;
            if(nums[mid] == target){
                return true;
            }else if(nums[mid] == nums[right]){
                right--;
            }else if(nums[mid] < nums[right]){
                if(nums[mid] < target && nums[right] >= target){
                    left = mid + 1;
                }else{
                    right = mid - 1;
                }
            }else{
                if(nums[left] <= target && nums[mid] > target){
                    right = mid -1;
                }else{
                    left = mid+1;
                }
            }
        }
        return false;
    }
};

 

posted @ 2018-06-12 09:01  妖域大都督  阅读(114)  评论(0编辑  收藏  举报