81 Search in Rotated Sorted Array II
2016-06-07 12:56
405 查看
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 题的区别就是http://www.cnblogs.com/li-daphne/p/5566373.html
就是数组中的数可以是重复的。
比如
/**
1. 1.. 1... 2 3 4 5
5 1. 1.. 1... 2 3 4
4 5 1. 1.. 1... 2 3
3 4 5 1. 1.. 1... 2
2 3 4 5 1. 1.. 1...
1... 2 3 4 5 1. 1..
1.. 1... 2 3 4 5 1.
*/
1 3 1 1 1
1 1 3 1 1
1 1 1 3 1
1 1 1 1 3
3 1 1 1 1
图画的不好,完美的避开了所有演示。
在将nums利用mid分为左右两部分后,你不能通过nums[mid]<num[right]来判断右边是有序的,或利用nums[mid]>nums[right]判断左边是有序的。
如果nums[mid]<=nums[right]分为两部分:
如果nums[mid]<nums[right],则右边是有序,利用排除法现在有序的部分搜索;后再无序的部分搜索。
如果nums[mid]==nums[right],right--后再看下一步就行了。
-----
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 题的区别就是http://www.cnblogs.com/li-daphne/p/5566373.html
就是数组中的数可以是重复的。
比如
/**
1. 1.. 1... 2 3 4 5
5 1. 1.. 1... 2 3 4
4 5 1. 1.. 1... 2 3
3 4 5 1. 1.. 1... 2
2 3 4 5 1. 1.. 1...
1... 2 3 4 5 1. 1..
1.. 1... 2 3 4 5 1.
*/
1 3 1 1 1
1 1 3 1 1
1 1 1 3 1
1 1 1 1 3
3 1 1 1 1
图画的不好,完美的避开了所有演示。
在将nums利用mid分为左右两部分后,你不能通过nums[mid]<num[right]来判断右边是有序的,或利用nums[mid]>nums[right]判断左边是有序的。
如果nums[mid]<=nums[right]分为两部分:
如果nums[mid]<nums[right],则右边是有序,利用排除法现在有序的部分搜索;后再无序的部分搜索。
如果nums[mid]==nums[right],right--后再看下一步就行了。
-----
bool search_2(vector<int> &nums,int target){ if(nums.size()==0) return false; int left = 0; int right = nums.size()-1; while(left<=right){ int mid = (left+right)/2; if(nums[mid]==target) return true; else if(nums[mid]<nums[right]){ //我们已经直到数组的右边是有序的, if(nums[mid]<target && target <=nums[right])//判断有序的数组是不是存在target,方法是? left = mid+1; else right = mid-1; }else if(nums[mid]>nums[right]){ //这里我们假定数组左边的是有序的 if(target >=nums[left] && target<=nums[mid])///判断左边 有序的数组是不是存在target,方法是? right = mid-1; else left = mid+1; }else{ ///nums[mid]==nums[right], right左移一位,再试一试 right--; } } return false; }
相关文章推荐
- WEB站点性能优化实践
- SQl之PreparedStatement与Statement的区别---------( 二 )
- CodeChef 2016年6月问题
- mysql5.6 主从配置
- scanf、gets、getchar、cin、cin.get、cin.getline、getline总结
- POJ-3087- Shuffle'm Up(字符串模拟)
- PAT 1110
- java.lang.IllegalThreadStateException异常原因解析
- 常见浏览器兼容性问题与解决方案
- xml知识点
- Mybatis 异常: The content of elements must consist of well-formed character data or markup
- git 查看远程分支、本地分支、删除本地分支
- CodeForces 669A Little Artem and Presents
- R语言实战:机器学习与数据分析源代码1
- Cookie和Session的区别详解
- 贝叶斯推断
- Android自定义View实现可以拖拽的GridView
- javascript 输出 素数/质数
- SQl之PreparedStatement用法---------( 一 )
- 用HTML5的canvas实现抽奖刮刮卡的效果(只需十几行代码)