[LeetCode]153. Find Minimum in Rotated Sorted Array

来源:互联网 发布:苹果手机提高数据网速 编辑:程序博客网 时间:2024/06/11 06:37

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

You may assume no duplicate exists in the array.

顺序查找的方法:

public class Solution {    public int findMin(int[] nums) {        if (nums.length == 1) return nums[0];        int res = nums[0];        for (int i = 0; i < nums.length-1;i++){        if(nums[i] > nums[i+1]){            res = nums[i+1];            break;            }        }        return res;    }}
二分查找的方法:

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



0 0