LeetCode153题

LeetCode153题_第1张图片

public static int findMin(int[] nums) {
        if (nums.length == 1)return nums[0];
        if (nums.length == 2)return Math.min(nums[0],nums[1]);
        if (nums[0] < nums[nums.length-1])return nums[0];
        int left = 0 ;
        int right = nums.length - 1;
        while (left < right){
            int mid = left + (right - left) / 2;
            System.out.println("mid" + mid);
            if (nums[mid] >= nums[left]){
                if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid+1]){
                   return nums[mid + 1];
                }else {
                    left = mid + 1;
                    System.out.println("left" + left);
                }
            }else {
                if (nums[mid] < nums[mid - 1] && nums[mid] < nums[mid + 1]){
                   return nums[mid];
                }else {
                    right = mid;
                    System.out.println("right" + right);
                }
            }
        }
        return -1;
    }

你可能感兴趣的:(LeetCode,leetcode,算法)