leetcode刷题日记——Find Minimum in Rotated Sorted Array II
2015-12-30 20:19
134 查看
Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
The array may contain duplicates.
问题分析:这个题目和上个题目的区别在于这里允许数组重复。需要区别处理的部分就是上题代码中的相等的情况,当出现middle和low位置的元素相等的时候,我们无法判断最小元素是处于前部分还是后部分,解决办法就是遍历整个数组寻找最小元素,实现代码如下:
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
The array may contain duplicates.
问题分析:这个题目和上个题目的区别在于这里允许数组重复。需要区别处理的部分就是上题代码中的相等的情况,当出现middle和low位置的元素相等的时候,我们无法判断最小元素是处于前部分还是后部分,解决办法就是遍历整个数组寻找最小元素,实现代码如下:
class Solution { public: int findMin(vector<int>& nums) { int size=nums.size(); if(size==1) return nums[0]; int low=0,high=size-1,middle=0; while(nums[low]>=nums[high]){ if(high-low==1) return nums[high]; middle=(low+high)/2; if(nums[middle]>nums[low]){ low=middle; }else if(nums[middle]<nums[low]){ high=middle; }else{ int minNum=nums[low]; for(int i=low;i<=high;i++){ if(minNum>nums[i]) minNum=nums[i]; } return minNum; } } return nums[middle]; } };
相关文章推荐
- 安利一下翻*的东东QAQ
- tableView上有多个输入框时候,如何不让键盘挡住输入框
- linux虚拟机与win主机之间ping通以及其他网络设置
- 《Non-Negative Matrix Factorization for Polyphonic Music Transcription》译文
- hdu3416 Marriage Match IV(最短路+网络流)
- 五种循环
- 启动zookeeper时出现的问题
- Javascript面向对象及组件详细介绍(四)包装对象
- 脑机接口技术的未来之驳
- pow()函数和直接用乘法的性能比较——以camel函数为例
- jquery datatable + backbone 的重构。
- Brainiac Designer
- android阅读器里的 txt 文本处理分页功能的实现:
- Qt的Model/View (二)
- 图书馆充电位置爆满解决办法
- 开发很有用的地址
- Intent 的传值,取值,打电话等。。
- 【splay】BZOJ 1507:[NOI2003]Editor
- error:LNK2005 已经在*.obj中定义
- 梦醒