7/26/2020

[LeetCode] 162. Find Peak Element

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

Time Complexity : O ( Log N )
class Solution:
    def findPeakElement(self, nums: List[int]) -> int:
        left, right = 0, len(nums) - 1
        
        if len(nums) <= 1:
            return 0
        
        if nums[left] > nums[left+1]:
            return left
        
        if nums[right] > nums[right-1]:
            return right
        
        while left < right:
            mid = left + (right - left)
            
            if nums[mid-1] < nums[mid] > nums[mid+1]:
                return mid
            elif nums[mid-1] < nums[mid] < num[mid+1]:
                # peak exists on the end of the ascending sequence
                left = mid + 1
            else:
                # peak exists on the begining of descending sequence
                right = mid - 1
        
        return right

No comments:

Post a Comment