[LeetCode] Find Minimum in Rotated Sorted Array II
2015-07-19 17:57
363 查看
This problem is more or less the same as Find Minimum in Rotated Sorted Array. And one key difference is as stated in the solution tag. That is, due to duplicates, we may not be able to throw one half sometimes. And in this case, we could just apply linear search and the time complexity will become
The idea to solve this problem is still to use invariants. We set
If
If
If
The code is as follows.
O(n).
The idea to solve this problem is still to use invariants. We set
lto be the left pointer and
rto be the right pointer. Since duplicates exist, the invatiant is
nums[l] >= nums[r](if it does not hold, then
nums[l]will simply be the minimum). We then begin binary search by comparing
nums[l], nums[r]with
nums[mid].
If
nums[l] = nums[r] = nums[mid], simply apply linear search within
nums[l..r].
If
nums[mid] <= nums[r], then the mininum cannot appear right to
mid, so set
r = mid;
If
nums[mid] > nums[r], then
midis in the first larger half and
ris in the second smaller half, so the minimum is to the right of
mid: set
l = mid + 1.
The code is as follows.
class Solution { public: int findMin(vector<int>& nums) { int l = 0, r = nums.size() - 1; while (nums[l] >= nums[r]) { int mid = (l & r) + ((l ^ r) >> 1); if (nums[l] == nums[r] && nums[mid] == nums[l]) return findMinLinear(nums, l, r); if (nums[mid] <= nums[r]) r = mid; else l = mid + 1; } return nums[l]; } private: int findMinLinear(vector<int>& nums, int l, int r) { int minnum = nums[l]; for (int p = l + 1; p <= r; p++) minnum = min(minnum, nums[p]); return minnum; } };
相关文章推荐
- Android中打开raw目录下的数据库文件
- 伪装隐藏Nginx,PHP版本号提升服务器安全性
- java微信上传永久素材
- Springmvc 配置json输出的几种方式
- codeforces 557D Vitaly and Cycle
- HTTP头部解释,HTTP头部详细分析,最全HTTP头部信息
- javaThread源码
- JAVA基础_Java反射
- hdu 1528 Card Game Cheater 最大匹配
- 屏蔽控制台应用程序窗口
- bootstrap 笔记01
- GCC 参数详解
- Linux环境下段错误的产生原因及调试方法小结
- IOS计算文字高度
- bootstrap模态框和select2合用时input无法获取焦点
- badboy+jMeter+jProfile软件测试工具介绍(一)
- 【thinkphp3.1.x】thinkphp3.1.x中有关redis缓存相关的文件
- 关于hibernate的一些恶心的小地方报错(持续更新)
- 系统重装后,Mysql数据库重装加载原来数据库
- Linux下的GitHub安装与简单配置教程