반응형
Find Peak Element
A peak element is an element that is strictly greater than its neighbors.
Given a 0-indexed integer array nums
, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞
. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n)
time.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
Constraints:
1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
nums[i] != nums[i + 1]
for all validi
.
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
left = 0
right = len(nums)-1
while left < right :
mid = (left + right) // 2
if nums[mid] < nums[mid + 1] :
left = mid + 1
else :
right = mid
return left
문제는 주변보다 높은 수의 인덱스를 찾는 문제. 문제의 가장 마지막 부분, O(log n) 으로 푸시오. 를 눈여겨 보자.
이진탐색이 가장 먼저 떠오르는 문제 풀이이다. 이 코드는 left >= right 가 되면 자연스레 끝이 나게 되는데, 대부분 left = right 가 될 것이다.
문제는 주변의 있는 수보다 높은 수를 찾는 문제이기 때문에 중복 정답이 허용된다. 따라서 이정도로만 설계해도 정답으로 통과된다.
반응형
'알고리즘 스터디' 카테고리의 다른 글
[Leetcode/파이썬] 13. Roman to Integer (0) | 2025.07.03 |
---|---|
[Leetcode/파이썬] 236. Lowest Common Ancestor of a Binary Tree (0) | 2025.07.03 |
[Leetcode/파이썬] 190. Reverse Bits (2) | 2025.07.03 |
[Leetcode/파이썬] 3. Longest Substring Without Repeating Characters (0) | 2025.06.04 |
[Leetcode/파이썬] 153. Find Minimum in Rotated Sorted Array (1) | 2025.06.04 |