LeetCode 题解(62): 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.

题解:最小值永远出现在未排好序的一半。若low < mid < high,则两半都未排好序的状态,最小值为low。若只剩两个元素,最小值为两者中的小的。

C++版:

class Solution {
public:
    int findMin(vector<int> &num) {
        int low = 0, high = num.size()-1;
        if(low == high)
            return num[low];

        while(low <= high) {
            int mid = (low + high) / 2;
            if(num[mid] > num[low] && num[mid] > num[high]) 
                low = mid;
            else if(num[mid] < num[low] && num[mid] < num[high]) {
                high = mid;
            } else if(num[mid] > num[low] && num[mid] < num[high]) {
                return num[low];
            } else if(num[mid] == num[low]) {
                if(num[low] < num[high])
                    return num[low];
                else
                    return num[high];
            }
        }
    }
};

Java版:

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

Python版:

class Solution:
    # @param num, a list of integer
    # @return an integer
    def findMin(self, num):
        if len(num) == 1:
            return num[0]
            
        low = 0
        high = len(num)-1
        while low <= high:
            mid = (low + high) / 2
            if num[low] < num[mid] and num[mid] < num[high]:
                return num[low]
            elif num[low] < num[mid] and num[high] < num[mid]:
                low = mid
            elif num[low] > num[mid] and num[high] > num[mid]:
                high = mid
            else:
                if num[low] < num[high]:
                    return num[low]
                else:
                    return num[high]


你可能感兴趣的:(LeetCode,Algorithm)