LeetCode OJ 81 Search in Rotated Sorted Array II
2015-07-11 11:24
295 查看
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.
思路:假如有重复的元素后,需要在进行first和mid进行更为细致的划分。当first>mid时,显然前半段非顺序,则后半段必为顺序(可能包含重复);当first==mid时,则前半段必非顺序且包含重复元素,只需要将first不断++即可找到逆序区间;first<mid时,则前半部分为顺序区间。
代码如下
运行时间:8ms
运行结果分析:
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.
思路:假如有重复的元素后,需要在进行first和mid进行更为细致的划分。当first>mid时,显然前半段非顺序,则后半段必为顺序(可能包含重复);当first==mid时,则前半段必非顺序且包含重复元素,只需要将first不断++即可找到逆序区间;first<mid时,则前半部分为顺序区间。
代码如下
class Solution { public: bool search(vector<int>& nums, int target) { int first=0; int last=nums.size()-1; while(first!=last) { const int mid=first+(last-first)/2; if(nums[mid]==target) return true; if(nums[first]<nums[mid]) { if(nums[first]<=target&&target<nums[mid]) last=mid; else first=mid+1; } else if(nums[first]>nums[mid]) { if(nums[mid]<target&&target<=nums[last]) first=mid+1; else last=mid; } else { first++; } } if(nums[last]==target) return true; else return false; } };
运行时间:8ms
运行结果分析:
相关文章推荐
- windows 环境下 ping 加时间戳 记日志
- 微信二次开发接入,附带后台框架
- 什么场景Hbase
- Python的ABC模块
- 信任在哪里?
- 关于SQL server 2012无法打开物理文件“某某某”,操作系统错误5 :"(拒绝访问)"。(Microsoft SQL Server,错误 5120)
- 解决 HP Deskjet 1000 打印字体模糊
- 全局变量和静态变量分析
- smartSvn ignore配置
- android training Supporting Different Screens
- 如何根据梯度重建原始图像以及图像重建常用算法?
- 简单的php-mvc设计
- cmd /c和cmd /k
- Objective-C语法之代码块(block)的使用
- ios UIButton 文字左边,图片右边排列
- ping通但上不了网的一个解决方法
- 薄慕明谈创新
- Android设置透明、半透明等效果
- nginx常用伪静态设置
- 初学JDBC,防SQL注入简单示例