首先,直接找最小元素也能过
function minNumberInRotateArray(rotateArray) { return Math.min.apply(Math,rotateArray); }
二分查找
注意两点:
- 对于数组[5 6 1 2 3 4], rotateArray[mid] < rotateArray[high], 说明答案在[low, mid]区间,但是arr[mid] 有可能是答案所以high = mid,而不是high = mid-1;
- rotateArray[mid] = rotateArray[high]
如果是 1 0 1 1 1, rotateArray[mid] = rotateArray[high] = 1, 答案在左边
如果是 1 1 1 0 1, r otateArray[mid] = rotateArray[high] = 1, 答案在右边
所以这种情况,不能确定答案在左边还是右边,那么就让high--;慢慢缩少区间,一个个试,同时也不会错过答案。function minNumberInRotateArray(rotateArray) { if(rotateArray.length === 0) return 0; let low = 0; let high = rotateArray.length - 1; while(low < high){ let mid = Math.floor((low + high) / 2); if(rotateArray[mid] > rotateArray[high]){ low = mid + 1; }else if(rotateArray[mid] < rotateArray[high]){ high = mid; }else{ high--; } } return rotateArray[low]; }