Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

81. Search in Rotated Sorted Array II

$
0
0

题目

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.

思路

这道题目,如果仅仅是实现,是很简单的,最坏情况O(n),我们知道在有序数组的情况下,二分搜索的时间复杂度是O(logn),那么在存在反转的情况下,能否使用二分搜索呢?答案是肯定的,唯一的区别就是三个索引值确定需要修改:left,right,mid

代码

class Solution {
public:
    bool search(vector<int>& nums, int target) {
        if(nums.empty())
            return false;
        int l=0,r=nums.size()-1;
        int mid = 0;
        while(l<r)
        {
            mid = (l+r)/2;
            if(nums[mid]==target)//如果相等
                return true;
            if(nums[mid]>nums[r])//如果大于
            {
                if(nums[mid]>target&&nums[l]<=target)
                    r=mid-1;
                else
                    l=mid+1;
            }
            else if(nums[mid]<nums[r])//如果小于
            {
                if(nums[mid]<target&&nums[r]>=target)
                    l=mid+1;
                else
                    r=mid-1;
            }
            else //如果等于
                r--;
        }
        return nums[l]==target?true:false;

    }
};
作者:u010665216 发表于2017/10/30 16:08:19 原文链接
阅读:93 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>