剑指offer——6.旋转数组的最小数字
2017-08-04 15:33
274 查看
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
代码
解法1
思路:直接将数组按从小到大排序,返回第一个元素即可。function minNumberInRotateArray(rotateArray) { // write code here rotateArray.sort(function(a,b){ if(a<b) return -1; else return 1; }); return rotateArray[0]; }
解法2
思路:采用二分法解答这个问题,需要考虑3种情况数组为空
部分旋转,例如由(1,2,3,4,5)旋转为(3,4,5,1,2),此时只需要遍历数组,找到当前数比前面的数小的数即可。
完全旋转,例如由(1,2,3,4,5)旋转为(1,2,3,4,5),此时第一个数最小。
function minNumberInRotateArray(rotateArray) { if(rotateArray.length===0){ return 0; } if(rotateArray.length===1){ return rotateArray[0]; } var index=parseInt(Math.floor((rotateArray.length)/2)); var left=rotateArray.slice(0,index); var right=rotateArray.slice(index); var recuArray;//rotateArray[index-]>=rotateArray[0]?right:left; if(rotateArray[index-1]<rotateArray[0]){ recuArray=left; }else { //是否还是旋转数组 if(right[0]<=right[right.length-1]) return right[0]; else recuArray=right; } return minNumberInRotateArray(recuArray); }
相关文章推荐
- 剑指Offer_11_旋转数组的最小数字
- [置顶] 剑指offer:第8题旋转数组的最小数字
- 剑指offer之面试题8旋转数组的最小数字
- 剑指offer__03__旋转数组的最小数字
- 面试题08_旋转数组的最小数字——剑指offer系列
- 剑指offer_数组---旋转数组的最小数字
- 剑指offer——旋转数组的最小数字
- 《剑指offer》旋转数组的最小数字
- 《剑指Offer》面试题8:旋转数组的最小数字
- 《剑指Offer》面试题:旋转数组的最小数字
- 剑指offer系列-T8旋转数组的最小数字
- 剑指Offer系列-面试题8:旋转数组的最小数字
- 《剑指Offer》读书笔记06:旋转数组的最小数字
- 剑指offer(六)旋转数组的最小数字
- 《剑指offer》:[11]旋转数组的最小数字
- 剑指Offer系列---(11)旋转数组的最小数字
- 剑指offer-面试8:旋转数组的最小数字(查找和排序)
- 剑指offer—旋转数组的最小数字
- 旋转数组的最小数字——剑指offer
- 剑指offer(九)之旋转数组的最小数字