Find Peak Element
LeetCode 162 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Climb toward the higher neighbour.
ನಾನು 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
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.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
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.