LeetCode 153. Find Minimum in Rotated Sorted Array(旋转数组查找)

来源:互联网 发布:传奇的dbc数据 编辑:程序博客网 时间:2024/05/17 06:40

原题网址:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/

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 {    private int min(int[] nums, int from, int to) {        if (from == to) return nums[from];        if (nums[from] < nums[to]) return nums[from];        int m = (from+to)/2;        if (nums[m] > nums[to]) return min(nums, m + 1, to);        return min(nums, from, m);    }    public int findMin(int[] nums) {        return min(nums, 0, nums.length-1);    }}

方法二:二分法。

public class Solution {    public int findMin(int[] nums) {        int from = 0, to = nums.length-1;        while (nums[from]>nums[to]) {            int mid = (from+to)/2;            if (nums[mid] > nums[to]) from = mid + 1;            else to = mid;        }        return nums[from];    }}


0 0
原创粉丝点击