您的位置:首页 > 其它

Find Minimum in Rotated Sorted Array

2015-07-31 22:42 369 查看
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[] num) {
        if (num == null || num.length == 0) {
            return 0;
        }
        if (num.length == 1) {
            return num[0];
        }
        int start = 0, end = num.length - 1;
        while (start < end) {
            int mid = start + (end- start) / 2;
            if (mid > 0 && num[mid] < num[mid - 1]) {
                return num[mid];
            }
            //mid的值比start和end的值都大,所以转折点在右边
            //e.g[4,5,6,7,8,9,10,11,1,2,3]
            if (num[start] <= num[mid] && num[mid] > num[end]) {
                start = mid+1;
            //转折点在左边
            //e.g[8,1,2,3,4,5,6,7]
            } else {
                end = mid-1;
            }
        }
        return num[start];
    }
}


The minimum element must satisfy one of two conditions: 1) If rotate, A[min] < A[min - 1]; 2) If not, A[0]. Therefore, we can use binary
search: check the middle element, if it is less than previous one, then it is minimum. If not, there are 2 conditions as well: If it is greater than both left and right element, then minimum element should be on its right, otherwise on its left.

jiuzhang:

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


只看mid和end的值大小,mid的值如果比end的大,则,左边升序,转折点在mid右边:[4,5,6,7,8,9,10,11,1,2,3]

如果mid的值小于end,则左边升序,转折点在左边:[7,1,2,3,4,5,6]

public class Solution {
    public int findMin(int[] num) {
        if (num == null || num.length == 0) {
            return 0;
        }
        if (num.length == 1) {
            return num[0];
        }
        int start = 0, end = num.length - 1;
        while (start < end) {
            int mid = start + (end- start) / 2;
            if (num[mid]>num[end]) {
                start = mid+1;
            } else {
                end = mid;
            }
        }
        return num[start];
    }
}


find minimum in rotated sorted array II有重复元素:
https://leetcode.com/discuss/19746/my-pretty-simple-code-to-solve-it
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: