Leetcode|Find Minimum in Rotated Sorted Array II(有重复元素的二分查找)
2015-08-01 17:15
465 查看
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.
解法1:
解法2:思路更加清晰,易懂。
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.
解法1:
//自己想的,遇到首尾和mid相等的,检验mid是左边还是在右边,检验时只能挨个查找。 int findMin1(vector<int>& nums) { int n=nums.size(); if(n==1) return nums[0]; int first=0,last=n-1; while(first<last){ int mid=(first+last)/2; if(nums[last]<nums[mid]) first=mid+1; else{ if(nums[first]==nums[mid]&&nums[mid]==nums[last]){ int l=mid; while(l<last&&nums[++l]==nums[last]);//检验mid是否在右边 if(l==last) last=mid; else first=mid+1; } else last=mid; } } return nums[first]; }
解法2:思路更加清晰,易懂。
//按照陈老师的优化了思路,直接把开始的first(nums[first]==nums[last])的重复的去掉。 //后面和没重复的一样了! int findMin(vector<int>& nums) { int n=nums.size(); if(n==1) return nums[0]; int first=0,last=n-1; while(first<last){ while(nums[first]==nums[last]&&first<last){ first++; } int mid=(first+last)/2; if(nums[last]<nums[mid]) first=mid+1; else last=mid; } return nums[first]; }
相关文章推荐
- WIN10安装与升级的方法
- Redis 事务
- Android基础之intent传值方法和传递大量数据方案
- CSS基础-21CSS定位-浮动的应用,实现瀑布流布局
- Shell 学习11 - Shell 字符串
- 10.通知(NSNotification)
- CodeForces_435B_C
- 地理信息产业现状:也许,我们正处在最好的年代
- 学习笔记——Java数字处理类
- hdu4549 斐波那契数列(乘法递推) + 欧拉定理 (快速幂,模幂)
- 深入浅出Mybatis-与Spring集成
- hdoj 2111 Saving HDU
- 基本排序方法之五——简单选择排序
- HDU 1823 Luck and Love
- Redis Sentinel初体验
- Android核心基础-7.Android 网络通信-4.获取网络XML,JSON
- 字符串的比较
- zoj 1526 Big Number (N阶乘的位数)
- 51nod1189
- 动态库的动态链接(error while loading shared libraries,cannot open shared object file)