LeetCode(154) Find Minimum in Rotated Sorted Array II
2024-09-29 11:49:33
题目
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.
Subscribe to see which companies asked this question
分析
在含有重复元素的旋转有序序列中查找最小元素。
与上一题类似,LeetCode(153) Find Minimum in Rotated Sorted Array 153题中的旋转有序数组不包含重复元素,而此题允许重复元素,增加了一点难度。
我想题目重点考察的还是沿用二分查找的方法解决,思路参考。
AC代码
class Solution {
public:
//方法一:使用stl库函数
int findMin1(vector<int>& nums) {
if (nums.empty())
return 0;
vector<int>::iterator iter = min_element(nums.begin(), nums.end());
return *iter;
}
//方法二:整个数列除一处为最大值到最小值的跳转外,为两部分的递增
int findMin2(vector<int>& nums)
{
if (nums.empty())
return 0;
if (nums.size() == 1)
return nums[0];
for (size_t i = 1; i < nums.size(); ++i)
{
if (nums[i - 1] > nums[i])
return nums[i];
}//for
//没有找到跳转元素,则序列无旋转
return nums[0];
}
int findMin(vector<int> &nums)
{
if (nums.empty())
return 0;
else if (nums.size() == 1)
return nums[0];
else{
int lhs = 0, rhs = nums.size() - 1;
while (lhs < rhs && nums[lhs] >= nums[rhs])
{
int mid = (lhs + rhs) / 2;
if (nums[lhs] > nums[mid])
rhs = mid;
else if (nums[lhs] == nums[mid])
++lhs;
else
lhs = mid + 1;
}//while
return nums[lhs];
}
}
};
最新文章
- 【20160722-20160728】NOI2016滚粗记&;&;酱油记&;&;游记
- delphi中线程应用之Synchronize
- ubuntu12.04网络配置
- FME中Cass扩展属性转Shp的方法
- ACM 2015年上海区域赛A题 HDU 5572An Easy Physics Problem
- 【转】ASP.NET MVC 入门教程列表
- div+css的叫法是不正确的
- 最短路径Shortest Path algorithm
- 记一次DG搭建过程中ORA-09925: Unable to createaudit trail file 错误
- 痞子衡嵌入式:飞思卡尔Kinetis系列MCU启动那些事(3)- KBOOT配置(FOPT/BOOT Pin/BCA)
- SQL varbinary varchar 互转
- CentOS安装mysql源码包
- We FALL ASleep At Night, We Do REST Right
- RNN总结
- 【树】Count Complete Tree Nodes
- Linux系列-Xshell连接本地VMware安装的Linux虚拟机
- 万网知您所需,“域”众不同--.link/.love/.help等一大波新顶级域来袭!
- overflow:auto产生的滚动条在安卓系统下能平滑滚动,而在ios下滚动不平滑
- sql 锁类型与锁机制
- Delphi XE8中开发DataSnap程序常见问题和解决方法 (二)想对DBExpress的TSQLDataSet写对数据库操作的SQL语句出错了!