[LeetCode]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.

1st solution: traverse array

Running Time: O(n)

2nd solution: Binary Search, use recursion here. (If we try to find an element in an array, usually we can use binary search)

Running Time: O(logn)

class Solution:
    # @param num, a list of integer
    # @return an integer
    def findMin(self, num):
        length = len(num)
        start=0
        end=length-1
        mid = (start+end)/2
        if length == 1 or length ==2:
            return min(num[start], num[end])#don't forget the situations when length is 1 or 2
        if start < end:
            if num[start] < num[end]:#deal with the un-rotated situation.
                return num[start]
            else:
                if num[start] < num[mid]:
                    return self.findMin(num[mid+1:])
                elif num[start] > num[mid]:
                    return self.findMin(num[:mid+1])
                else:
                    return num[start]


查找问题最直观的是遍历整个数组,但是运行时间O(n)通常难以被接受。

最常用的的使用二分查找,O(logn)的时间是比较理想的。

这里使用递归来实现,可以采用模板:

1. 边界条件。

2. 退出条件。

3. 缩小查找范围。


你可能感兴趣的:(LeetCode,python,search,binary,recursion)