博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode之Search in Rotated Sorted Array II (Java)
阅读量:2344 次
发布时间:2019-05-10

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

摘自

[LeetCode] Search in Rotated Sorted Array II (Java)

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.

Analysis

This problem is similar to “Search in Rotated Sorted Array”. But there could be duplicates.

In problem “Search in Rotated Sorted Array”, we compare A[left] with A[mid] to determine which part does not contains the rotate pivot. But in this problem, A[left] could be equal to A[mid]. To solve this problem, we can let just add 1 to left when we face A[left] == A[mid] and continue the algorithm.

public class Solution {    public boolean search(int[] A, int target) {        int start = 0;        int end = A.length - 1;        while (start <= end) {            int mid = (start + end) / 2;            if (A[mid] == target)                return true;            if (A[start] < A[mid]) {                if (target >= A[start] && target < A[mid])                    end = mid - 1;                else                    start = mid + 1;            } else if (A[start] > A[mid]) {                if (target > A[mid] && target <= A[end])                    start = mid + 1;                else                    end = mid - 1;            } else                start++;        }        return false;    }}

Complexity

The worst case complexity will become  O(n) O(n).

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

你可能感兴趣的文章
在ros底下安装opencv
查看>>
PHP页面纯静态化与伪静态化
查看>>
分享网页到微信朋友圈,显示缩略图的方法
查看>>
PHP参数类型限制
查看>>
IOS博客项目搭建-12-刷新数据-显示最新的微博数提示
查看>>
Laravel5 Markdown 编辑器使用教程
查看>>
php文件上传与下载
查看>>
Python3学习教程
查看>>
Python3学习笔记01-第一个Python程序
查看>>
Laravel5开发学生管理系统
查看>>
Laravel5学生成绩管理系统-01-安装-建表-填充数据
查看>>
Mac OSX下使用apt-get命令
查看>>
Mac下安装PHP的mcrypt扩展的方法(自己总结的)
查看>>
关于html_entity_decode、空格 以及乱码
查看>>
Box2d no gravity
查看>>
mario collision
查看>>
tiled 地图工具
查看>>
小游戏
查看>>
旋转关节绳子
查看>>
射箭box2d
查看>>