Find Minimum in Rotated Sorted Array

来源:互联网 发布:数据库全文检索 编辑:程序博客网 时间:2024/05/21 13:54

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.


 Notice

You may assume no duplicate exists in the array.


Example

Given [4, 5, 6, 7, 0, 1, 2] return 0


public class Solution {    /**     * @param nums: a rotated sorted array     * @return: the minimum number in the array     */    public int findMin(int[] num) {        if (num == null || num.length == 0) {            return -1;        }        int start = 0;        int end = num.length - 1;        //case 1: (1,2,3,4,5) 成一条不间断的线        if (num[end] > num[start]) {            return num[start];        }        //case 2: two lines in two seperate places        while (start + 1 < end) {            int mid = start + (end - start) / 2;            if (num[mid] > num[0]) { //increasing                start = mid;            } else {                end = mid;            }        }        if (num[start] < num[end]) {            return num[start];        } else {            return num[end];        }    }}


0 0