[Leetcode] 162. Find Peak Element

whitehousechef·2025년 3월 10일

https://leetcode.com/problems/find-peak-element/description/?envType=study-plan-v2&envId=top-interview-150

initial

one v impt condition is that the edges are negative infinity. So if u have like 1,2,1,3,5,6,7. Value 7 is still valid for binar ysearch condition.

So I almost got the condition right dam. I thought

            if nums[mid-1]<nums[mid]<nums[mid+1]:

But we get wrong error and index out of range. We just have to check if we are on ascending or descending slope (cur idx and cur idx +1).

wonder of index out of range

Now wont there be an index out of range error?

When we are comparing nums[mid] with nums[mid + 1], we are checking the right side of the current mid. This check is safe because we only do it when mid < len(nums) - 1.
If mid is at the last index (mid = len(nums) - 1), we will not compare nums[mid] with nums[mid + 1] because the condition mid < len(nums) - 1 will not be true.

Like logically, left and right take up 2 indexes so at the extreme end, mid is at len()-2 and right is at len()-1.

solution

class Solution:
    def findPeakElement(self, nums: List[int]) -> int:
        left,right=0,len(nums)-1
        while left<right:
            mid = left +(right-left)//2
            if nums[mid]<nums[mid+1]:
                left=mid+1
            else:
                right=mid
        return left

complexity

log n time
1 space

0개의 댓글