前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 81 Search in Rotated Sorted Array II

Leetcode 81 Search in Rotated Sorted Array II

作者头像
triplebee
发布2018-01-12 14:56:21
5810
发布2018-01-12 14:56:21
举报

Follow up for "Search in Rotated Sorted Array":

What if duplicates are allowed?

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

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

在循环错位的有序数组中进行搜索,与33题类似

https://cloud.tencent.com/developer/article/1019304

不同的是元素可能重复,

当遇到等于的时候,只能一个个地缩小区间,而不能以log复杂度减小,所以在最坏情况下,效率会退化为O(n).

代码语言:javascript
复制
class Solution {
public:
    bool search(vector<int>& nums, int target) {
        int l=0,r=nums.size()-1;
        while(l<=r)
        {
            int mid=(l+r)>>1;
            if(nums[mid]==target) return true;
            if(nums[mid]<nums[l])
            {
                if(target<nums[l] && target>nums[mid])
                    l=mid+1;
                else
                    r=mid-1;
                    
            }
            else if(nums[mid]>nums[l])
            {
                if(target>=nums[l] && target<nums[mid])
                    r=mid-1;
                else
                    l=mid+1;
            }
            else
                l++;  //mid和l值相等,无法获知mid的位置
        }
        return false;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-09-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档