旋转数组的最小数字
来源:互联网 发布:搞笑文案知乎 编辑:程序博客网 时间:2024/06/07 07:27
题目描述:
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0
思路1:最一开始,观察了规律,想都没想,直接遍历,写了一个O(n)的算法,,,遇到第一个下降的即是最小的元素,如果没有,那就是所有元素都相等或者全部旋转(或者说没有旋转),直接输出第一个。。。
代码1:
class Solution {public: int minNumberInRotateArray(vector<int> rotateArray) { if(rotateArray.size()==0) return 0; for(int i=1;i<rotateArray.size();i++){ if(rotateArray[i]<rotateArray[i-1]) return rotateArray[i]; } return rotateArray[0]; }};
思路2:问题显然没有那么简单,比O(n)复杂度更低的就是O(logn)了,得用二分搜索,一开始参照剑指offer写了一个很不简洁的程序,考虑了几个特殊情况,后来看讨论区,发现大神写的简洁的代码,又重写了一遍。。。
举个栗子:345|12是递增序列12345的旋转数组,可以分为前后两个递增数组,用二分搜索的思想,low和high分别是最左和最右的指针,center是中间的指针,如果nums[center]>nums[low],那么center元素在前半个递增数组中,最小元素,应该在其后面,low=high+1;如果nums[center]<nums[high],那么nums[center]在其前面的部分,high=center。
另外要考虑特殊情况,例如:
1、旋转数组10111,此时center和low和high是相等的,此时需要顺序搜索
2、旋转数组12345,此时low的值小于high的值,直接输出第一个元素
代码2:
class Solution {public: int minNumberInRotateArray(vector<int> rotateArray) { if(rotateArray.size()==0) return 0; int i=0; int j=rotateArray.size()-1; int center=(i+j)/2; if(rotateArray[i]<rotateArray[j]) return rotateArray[i]; while(center!=i){ if(rotateArray[center]>rotateArray[i]) i=center; else if(rotateArray[center]<rotateArray[j]) j=center; else{ for(int k=i+1;k<=j;k++){ if(rotateArray[k]<rotateArray[k-1]) return rotateArray[k]; } } center=(i+j)/2; } return rotateArray[j]; }};
上面的思路复杂化了,直接将中间元素和high的元素相比较,,再判断一下相等的情况,就简洁了许多,不用加那么多判断
代码3:
class Solution {public: int minNumberInRotateArray(vector<int> rotateArray) { if(rotateArray.size()==0) return 0; int low=0; int high=rotateArray.size()-1; int center; //二分搜索,center和high作比较而不用和low作比较 while(low<high){ center=(low+high)/2; if(rotateArray[center]>rotateArray[high]) low=center+1; else if(rotateArray[center]==rotateArray[high]) high--; else high=center; } return rotateArray[low]; }};
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- Android中MediaPlayer的常用方法
- 35-并发服务器(多进程)
- CCF NOI1017 价格查询
- Linux shell中运行可执行程序后加上&的作用
- Spark 2.1 , Method used to prevent multiple SparkContexts from being active at the same time
- 旋转数组的最小数字
- centos7下 tomcat8启动慢问题
- 关于UGUI的实例化
- Toorbar的基础使用
- apt update error "E: The package lists or status file could not be parsed or opened."
- 理解AES对称加密
- JS路由
- struts2工作原理
- 函数的调用过程,栈帧的创建和销毁。