Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 162 · Peak / Check Mid Sides

Find Peak Element

LeetCode 162 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Climb toward the higher neighbour.

நடுத்தரம்ArrayBinary Search
LeetCode இல் திற ↗

நான் Find Peak Element (LeetCode 162) ஐ இப்படித் தீர்த்தேன் — Peak / Check Mid Sides பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

If the middle element is smaller than its right neighbour, the slope is going up to the right, so a peak must exist on that side (the array ends in −∞). Otherwise a peak exists on the left. Binary search on that slope.

Approach

  1. 1

    Handle n = 1 and the two edges directly.

  2. 2

    Search inside [1, n−2].

  3. 3

    mid is higher than both neighbours → peak.

  4. 4

    Rising at mid → go right; falling → go left.

நான் எப்படித் தீர்த்தேன்

Binary search on the slopePythonO(log n) time · O(1) space
class Solution:
    def findPeakElement(self, nums: List[int]) -> int:
        #1,2,
        #1,3,5,6
        #4
        n = len(nums)
        if n==1:
            return 0
        if nums[0]>nums[1]:
            return 0
        if nums[n-1]>nums[n-2]:
            return n-1
        low = 1
        high = n-2
        while low<=high:
            mid = (low+high)//2
            if nums[mid]>nums[mid-1] and nums[mid]>nums[mid+1]:
                return mid #highest peak
            if nums[mid]>nums[mid-1]:
                low = mid+1 #search on the right to get the peak
            else:
                high = mid-1
        return -1
        
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Find Peak Element — அடிக்கடி கேட்கப்படும் கேள்விகள்

Find Peak Element பின்னாலுள்ள intuition என்ன?

If the middle element is smaller than its right neighbour, the slope is going up to the right, so a peak must exist on that side (the array ends in −∞). Otherwise a peak exists on the left. Binary search on that slope.

Find Peak Element (LeetCode 162) ஐ எப்படித் தீர்ப்பது?

1. Handle n = 1 and the two edges directly. 2. Search inside [1, n−2]. 3. mid is higher than both neighbours → peak. 4. Rising at mid → go right; falling → go left.

Find Peak Element இன் time மற்றும் space complexity என்ன?

Time: O(log n). Space: O(1). (Accepted approach: Binary search on the slope.)

Find Peak Element இல் பொதுவான தவறுகள் என்ன?

Checking the ends first keeps mid−1 and mid+1 in range.