Sunday, August 23, 2015

Leetcode 153. Find Minimum in Rotated Sorted Array

https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/

One line for Python: return min(nums). The normal way is binary search.

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

        return num[low]
Run Time: 52 ms

No comments:

Post a Comment