【6】旋转数组 的最小数字
来源:互联网 发布:重庆知行科技学校 编辑:程序博客网 时间:2024/05/19 04:03
【6】旋转数组 的最小数字
- 时间限制:1秒
- 空间限制:32768K
- 本题知识点: 查找
题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
方法一:
算法代码:逐个遍历,时间复杂度为O(n),空间复杂度为O(1).
class Solution {public: int minNumberInRotateArray(vector<int> rotateArray) { if(rotateArray.empty()) return 0; //检查下降信号 int result=rotateArray[0]; for(int i=1;i!=rotateArray.size(); i++) { if(rotateArray[i]<result) return rotateArray[i]; } return result; }};
方法二:二分查找
时间效率为log(n);
class Solution {public: int minNumberInRotateArray(vector<int> rotateArray) { if(rotateArray.empty()) return 0; //非递减,可能为1 1 2 3 1 //二分查找 int l=0,h=rotateArray.size()-1; while(l<h) { int mid=(l+h)/2; //脉冲信号 if(rotateArray[mid+1]<rotateArray[mid]) return rotateArray[mid+1]; if(rotateArray[mid]>rotateArray[l]) l=mid; else if(rotateArray[mid<rotateArray[l]]) h=mid; else l=l+1; } return rotateArray[l]; }};
方法三:
二分查找,设立标志位
class Solution {public: int minNumberInRotateArray(vector<int> rotateArray) { if(rotateArray.empty()) return 0; //非递减,可能为1 1 2 3 1 //二分查找 int l=0,h=rotateArray.size()-1; int temp=rotateArray[0];//标志位 while(l<h) { int mid=(l+h)/2; if(rotateArray[mid]>temp) l=mid+1; else if(rotateArray[mid]<temp) h=mid; else l=l+1; } return rotateArray[l]; }};
测试用例:{1,0,1,1,1} 和 {1,1, 1,0,1} 都可以看成是递增排序数组{0,1,1,1,1}的旋转。
- 测试用例1:
[6501,6828,6963,7036,7422,7674,8146,8468,8704,8717,9170,9359,9719,9895,9896,9913,9962,
154,293,334,492,1323,1479,1539,1727,1870,1943,2383,2392,2996,3282,3812,3903,4465,4605,4665,4772,4828,5142,5437,5448,5668,5706,5725,6300,6335]
对应输出应该为:154
- 测试用例2:
- 测试用例:[],[2],[3,1],[3,1,2]. [1,2]该情况不行,程序只能希望输入一定为旋转过的数组。
1 0
- 【6】旋转数组 的最小数字
- 6、旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 编译安装php扩展fileinfo
- js 里 escape,encodeURI,encodeURIComponent编码方法之我见
- Hibernate事务与并发问题处理(悲观锁与乐观锁)
- 谷歌开源项目风格指南笔记(上)
- AndroidManifest.xml文件详解
- 【6】旋转数组 的最小数字
- js同源策略
- http协议响应状态码大全以及常用状态码
- 最接近的数
- Cloudera:Hue监控页面的时间显示问题
- 分类算法中的ROC与PR指标
- UNIX/Linux系统取证之信息采集案例
- A guide to Python's function decorators
- I.MX6Q(TQIMX6Q/TQE9)学习笔记——LTIB安装配置