博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Search in Rotated Sorted Array II
阅读量:4070 次
发布时间:2019-05-25

本文共 1337 字,大约阅读时间需要 4 分钟。

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.

出现重复的时候,因为重复的次数我们无从得知,原数组旋转折叠的位置我们也无从得知,所以最后折叠后的状态我们也就无从得知,所以我们无法去按着Search in Rotated Sorted Array的判断标准去判断哪部分有序,设想一种情形1,1, 1,2,1,1,1,恰好左中右都是1,这时我们 ++左下标,--右下标,为什么这样我们不会将这个值跳过呢? 就是说,凭什么我们说除却这两个位置,在两者之间就一定还存在这个值?当然能,因为我们进入的条件是左中右相等,所以我们可以把首尾的值都略过,进行下一次循环。

class Solution {public:    bool search(int A[], int n, int target)    {        if(0 == n) return false;        int left = 0;         int right = n - 1;        while(left <= right)        {            int midle = (left + right) >> 1;            if(A[midle] == target) return true;            if(A[left] == A[midle] && A[midle] == A[right])            {               ++left;               --right;            }            else if(A[left] <= A[midle])            {                if(A[left] <= target && target  < A[midle])                {                    right = midle - 1;                }                else                left = midle + 1;            }            else {                if(A[midle] < target && target <= A[right])                    left = midle + 1;                else                     right = midle - 1;            }        }        return false;    }};

转载地址:http://helji.baihongyu.com/

你可能感兴趣的文章
链接点--数据结构和算法
查看>>
servlet中请求转发(forword)与重定向(sendredirect)的区别
查看>>
Spring4的IoC和DI的区别
查看>>
springcloud 的eureka服务注册demo
查看>>
eureka-client.properties文件配置
查看>>
MODULE_DEVICE_TABLE的理解
查看>>
platform_device与platform_driver
查看>>
platform_driver平台驱动注册和注销过程(下)
查看>>
.net强制退出主窗口的方法——Application.Exit()方法和Environment.Exit(0)方法
查看>>
c# 如何调用win8自带的屏幕键盘(非osk.exe)
查看>>
build/envsetup.sh 简介
查看>>
C++后继有人——D语言
查看>>
Android framework中修改或者添加资源无变化或编译不通过问题详解
查看>>
linux怎么切换到root里面?
查看>>
linux串口操作及设置详解
查看>>
安装alien,DEB与RPM互换
查看>>
linux系统下怎么安装.deb文件?
查看>>
编译Android4.0源码时常见错误及解决办法
查看>>
Android 源码编译make的错误处理
查看>>
linux环境下C语言中sleep的问题
查看>>