剑指Offer 11 旋转数组最小数字

剑指Offer 11 旋转数组最小数字

  • 错误代码
//部分有序数组查找: 改进二分法
class Solution {
    public int minArray(int[] numbers) {
        //单元素
        if(numbers.length==1) return numbers[0];
        //未旋转
        else if(numbers.length>1 
            && numbers[0]<numbers[numbers.length-1])
            return numbers[0];
        
        /*出错点*/
        /*去重复(左端、右端包含重复元素),需要每次将左右指针挪到最内侧重复元素位置处*/
        ......

        int mid = left + (right-left)/2;
        while(left < right-1) {
            //右端,选左边
            if(numbers[mid]<=numbers[left]) {
                right = mid;
            }
            //左端,选右边
            else if(numbers[mid]>=numbers[right]) {
                left = mid;
            }
            mid = left + (right-left)/2;
        }
        
        return numbers[right];
    }
}
  • 官方题解(二分法)
class Solution {
    public int minArray(int[] numbers) {
        int low = 0;
        int high = numbers.length - 1;
        while (low < high) {
            int pivot = low + (high - low) / 2;
            if (numbers[pivot] < numbers[high]) {
                high = pivot;
            } else if (numbers[pivot] > numbers[high]) {
                low = pivot + 1;
            } 
            /*去重复*/
            else {
                high -= 1;
            }
        }
        return numbers[low];
    }
}
posted @ 2020-07-22 09:06  CodeSPA  阅读(80)  评论(0编辑  收藏  举报