Search in Rotated Sorted Array II--LeetCode

来源:互联网 发布:美团数据分析工资 编辑:程序博客网 时间:2024/06/02 02:55

1.题目

Search in Rotated Sorted Array II

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.

2.题意

将升序数组旋转,找出target所在的下标,数组中可能有重复值

3.分析

类似Search in Rotated Sorted Array
允许重复值,可能出现两种情况
如[3 1 1] 和 [1 1 3 1],
当中间值等于最右值时,无法确定目标值3的所在范围
对于这种情况,只要把最右值左移并继续循环,一直移到不同值即可
这一步使得算法的复杂度由原先的O(logn)变成了O(n)

4.代码

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;            if(nums[mid] < nums[right])            {                if(nums[mid] < target && target <= nums[right])                    left = mid + 1;                else                    right = mid - 1;            }            else if(nums[mid] > nums[right])            {                if(nums[left] <= target && target < nums[mid])                    right = mid - 1;                else                    left = mid + 1;            }            else                --right;        }        return false;    }};
原创粉丝点击