Monday, August 24, 2015

Leetcode 162. Find Peak Element

https://leetcode.com/problems/find-peak-element/

The slick solution is to return the index of max number. The normal solution is to use binary search,

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

No comments:

Post a Comment