作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/

题目描述:

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false

Follow up:

  • This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
  • Would this affect the run-time complexity? How and why?

题目大意

在一个含有重复数字的旋转递增数组中,找出是否存在某个数字。

解题方法

很明显的二分查找的题目,是33. Search in Rotated Sorted Array的拓展题目,变的是加了一个可能含有重复数字。

这样的话,如果直接进行左右指针的比较就不知道向哪个方向搜索了,所以,需要在正式比较之前,先移动左指针,是他指向一个和右指针不同的数字上。然后再做33题的查找。

至于查找部分,可以这么考虑:首先nums[l] > num[r]认为是恒成立的。

如果mid指向的位置比nums[l]还大,那么说明l到mid是有序的,这个时候如果nums[l] <= target < nums[mid]说明要查找的在Mid前面,移动右指针;否则要查找的在mid后面,移动左指针。

如果mid指向的位置比nums[r]还小,那么说明mid到r是有序的,然后同样的进行比较操作就行了。

时间复杂度是O(N),空间复杂度是O(1).

class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
N = len(nums)
l, r = 0, N - 1
while l <= r:
while l < r and nums[l] == nums[r]:
l += 1
mid = l + (r - l) / 2
if nums[mid] == target:
return True
if nums[mid] >= nums[l]:
if nums[l] <= target < nums[mid]:
r = mid - 1
else:
l = mid + 1
elif nums[mid] <= nums[r]:
if nums[mid] < target <= nums[r]:
l = mid + 1
else:
r = mid - 1
return False

参考资料

https://leetcode.com/problems/search-in-rotated-sorted-array-ii/discuss/177150/Search-in-Rotated-Sorted-Array-I

日期

2018 年 10 月 20 日 —— 10月剩余的时间又不多了

最新文章

  1. iOS角度与弧度转换
  2. 限制textarea的字数(包括复制粘贴)
  3. Shell基础学习小结
  4. 在网站制作中随时可用的10个 HTML5 代码片段
  5. python 优雅的使用正则表达式 ~ 2
  6. php中常用设置
  7. OpenSSL命令---rsa
  8. python中使用ctypes调用MinGW生成的动态链接库(dll)
  9. HDU 4034 Graph(Floyd变形——逆向判断)
  10. sql中的 IF 条件语句的用法
  11. MyBatis DTD文件下载地址
  12. 什么是云?Iaas,Paas和SaaS
  13. CentOS7.3安装rz、sz命令
  14. Android 判断是否有声音在播放
  15. Confluence 6 删除和归档空间
  16. (转)MYSQL远程登录权限设置
  17. Python面向对象:获取对象信息
  18. Oracle 进入数据库 新增用户 修改密码方法
  19. mysql -&gt; 用户管理&amp;数据类型_04
  20. zepto 添加 animate组件

热门文章

  1. 【Redis集群原理专题】分析一下相关的Redis集群模式下的脑裂问题!
  2. Java中static关键字声明的静态内部类与非静态内部类的区别
  3. 云原生时代,为什么基础设施即代码(IaC)是开发者体验的核心?
  4. day07 Linux配置修改
  5. 大数据学习day39----数据仓库02------1. log4j 2. 父子maven工程(子spring项目的创建)3.项目开发(埋点日志预处理-json数据解析、清洗过滤、数据集成实现、uid回补)
  6. 虚拟机中安装centos系统的详细过程
  7. 从面试官的角度,聊聊java面试流程
  8. Angular Service设计理念及使用
  9. SpringBoot(2):运行原理
  10. 【Linux】【Shell】【Basic】字符串操作