旋转数组的最小数字
来源:互联网 发布:众途软件下载 编辑:程序博客网 时间:2024/05/22 01:48
题目描述:
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小数组。例如数组{3,4,5,1,2}是数组{1,2,3,4,5}的旋转数组,该数组的最小值为1。
思路解析:
- O(N)的算法
这种算法的思想就是遍历这个数组,由于这个数组是两部分有序的数组,因此遍历这个数组时当后一个数字小于前一个数字时,则后一个(即较小)一定为整个数组中最小的数字。
这种算法的思想很简单,但就是时间复杂度较大,因此不是很好的算法。
int minNumberInRotateArray(vector<int> rotateArray){ if (rotateArray.empty()) return -1; unsigned int i=0; for (; i<rotateArray.size()-1; i++) { if (rotateArray[i] > rotateArray[i+1]) break; } return rotateArray[i+1];}
- O(logN)的算法
这种算法思想类似于二分查找,首先每次找到数组中中间的数字mid,如果mid大于最左端left,说明最小数在mid的右侧区间,则改变left,置left为mid;如果mid小于数组右侧right,说明最小数在mid的左侧区间,则改变right为mid….当left的数字小于等于right的数字时,说明已经找到最小数,这个也是循环结束的条件
int minNumberInRotateArray(vector<int> rotateArray){ if (rotateArray.empty()) return -1; unsigned int left=0; unsigned int right=rotateArray.size()-1; unsigned int mid=left; while (rotateArray[left] >= rotateArray[right]) { if (right-left == 1) { mid = right; break; } mid = left+((right-left)>>1); if (rotateArray[mid]==rotateArray[left] && rotateArray[right]==rotateArray[mid]) return minNumberInRotateArray(rotateArray,left,right); if (rotateArray[mid] >= rotateArray[left]) left = mid; else if (rotateArray[mid] <= rotateArray[right]) right = mid; } return rotateArray[mid];}int minNumberInRotateArray(vector<int> rotateArray, int left, int right){ int min_v = rotateArray[left]; for (int i=left; i<=right; i++) min_v = min(rotateArray[i],min_v); return min_v;}
阅读全文
0 0
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 京东技术架构(二)构建需求响应式亿级商品详情页
- (ZT)string is utf-8
- 仿QQ点赞吹泡泡效果
- jq 分页展示数据,选中checbox将选中的id保存起来传给后台
- Python基于线程的并发编程
- 旋转数组的最小数字
- Oracle12c创建新用户提示公共用户名或角色无效
- Cause: InvokeDynamic not supported
- Twitter算法面试题详解(Java实现)
- 快速消费品企业TPM-营销费用管控系统应用实例
- RTSP Spec中文版(12-16)
- 面试题11数值的整数次方
- Linux下which、whereis、locate、find 命令的区别
- pecl oci8 error: oci.h: No such file or directory