剑指offer题解C++【6】旋转数组的最小数字
2017-07-26 22:58
405 查看
题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。解题思路
旋转数组可以分为两个有序的数组,最小元素就是这两个数组的分界点。可以用二分查找来解决:当数组大小为0时,返回0;
用istart,istop,imid分别指向第一个元素、最后一个元素和中间元素:
若中间元素比第一个元素和最后一个元素都大,则说明最小值在右侧,此时让istart指向中间元素的下一个元素;
否则,若中间元素小于最后一个元素且第一个元素大于最后一个元素(确保旋转),说明最小值在左侧,此时让istop指向中间元素;
否则,数组不是递增的,存在相同元素,比如{1,1,1,0,1},则遍历数组,找到最小值。
代码
class Solution { public: int minNumberInRotateArray(vector<int> rotateArray) { if (rotateArray.size() == 0) return 0; int istart = 0, istop = rotateArray.size() - 1; while (istart < istop){ if (istart + 1 == istop) return min(rotateArray[istart], rotateArray[istop]); int start = rotateArray[istart]; int stop = rotateArray[istop]; int imid = istart + ((istop - istart) >> 1); int mid = rotateArray[imid]; if (start < mid && mid > stop){ istart = imid + 1; } else if (start > stop && mid < stop){ istop = imid; } else{ int mymin = INT_MAX; for (int j = istart; j != istop + 1; j++){ mymin = min(mymin, rotateArray[j]); } return mymin; } } return rotateArray[istart]; } };
相关文章推荐
- 剑指offer第六题【旋转数组的最小数字】c++实现
- (C++)剑指offer-6:旋转数组的最小数字
- [牛客网,剑指offer,python] 旋转数组的最小数字
- 剑指offer面试题[8]-旋转数组的最小数字
- leetcode之Search in Rotated Sorted Array,剑指offer之旋转数组的最小数字
- 剑指Offer-旋转数组的最小数字
- 【剑指offer】六,旋转数组中的最小数字
- 剑指Offer:旋转数组的最小数字
- 剑指offer-旋转数组的最小数字
- 剑指Offer-旋转数组的最小数字
- 剑指Offer之 - 旋转数组的最小数字
- 剑指offer:旋转数组的最小数字 代码实现
- [牛客网,剑指offer,python] 旋转数组的最小数字
- 剑指offer之面试题8:旋转数组的最小数字
- [剑指Offer] 6.旋转数组的最小数字(二分法)
- 剑指offer-旋转数组的最小数字-二分查找法
- 剑指offer:旋转数组的最小数字
- 【九度OJ1386】|【剑指offer8】旋转数组的最小数字
- 剑指offer--旋转数组的最小数字
- 剑指offer8旋转数组的最小数字