【leetcode】Array——Search in Rotated Sorted Array II(81)
2016-02-26 11:54
507 查看
题目:
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.
思路:
借鉴前一题的思路,同样,先通过比较nums[mid]和nums[left],确定转折点是在左半侧还是右半侧。由于允许重复,所以会出现nums[mid]==nums[left],
这时候不能确定转折点的位置,比如[1,2,1,1,1]和[1,1,1,2,1]
所以这种情况仅作“简单处理”——left++,再重新循环判断。
代码:
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.
思路:
借鉴前一题的思路,同样,先通过比较nums[mid]和nums[left],确定转折点是在左半侧还是右半侧。由于允许重复,所以会出现nums[mid]==nums[left],
这时候不能确定转折点的位置,比如[1,2,1,1,1]和[1,1,1,2,1]
所以这种情况仅作“简单处理”——left++,再重新循环判断。
代码:
public boolean search(int[] nums, int target) { int left =0,right=nums.length-1; while(left<=right){ int mid = (left+right)/2; if(nums[mid]==target) return true; if(nums[mid]>nums[left]){//转折点在右侧 if(target<nums[mid]&&target>=nums[left]) right = mid -1; else left = mid +1; }else if(nums[mid]<nums[left]){//转折点在左侧 if(target>nums[mid]&&target<=nums[right]) left = mid +1; else right = mid -1; }else{//nums[mid]==nums[left],此时无法判断转折点的位置,所以仅把left+1 left++; } } return false; }leetcode上的解法和上述思路一样,有更详细的注释:https://leetcode.com/discuss/60618/neat-java-solution-using-binary-search
相关文章推荐
- 使用补丁修改DSDT/SSDT [DSDT/SSDT综合教程]
- Swift编程之枚举类型详解
- SpringMVC的各种参数绑定方式
- ScrollView跳至前一个或者指定位置
- spring官网下载地址
- windows7下virtualBox配置识别usb
- Nginx的alias的用法及与root的区别
- pthread_create()
- iOS 9 学习系列: Storyboard References
- 使用spring @Scheduled注解执行定时任务、
- SQL中的where条件,在数据库中提取与应用浅析
- 常见模块(一)
- jQuery 遍历函数
- 接口,抽象类
- GCM Configuration
- ubuntu 创建桌面图标执行应用
- 代理模式的简单例子
- 如何正确的命名软件版本号
- C语言中 \ 的作用
- Python time、datetime、os、random、sys、hashlib、json、shutil、logging、paramiko、subprocess、ConfigParser、xml、shelve模块的使用