본문 바로가기

코딩 테스트/LeetCode

Medium - Find Peak Element

728x90

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

 

Find Peak Element - LeetCode

Can you solve this real interview question? 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,

leetcode.com

문제 설명

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.

 

Constraints:

  • 1 <= nums.length <= 1000
  • -2 ** 31 <= nums[i] <= 2 ** 31 - 1
  • nums[i] != nums[i + 1] for all valid i.

예시

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.

풀이

class Solution:
    def findPeakElement(self, nums: List[int]) -> int:
        n = len(nums)
        neg_inf = -float('inf')

        l, r = 0, n-1
        
        while l <= r:
            mid = int((l + r) / 2)

            left_val = nums[mid - 1] if mid - 1 >= 0 else neg_inf
            right_val = nums[mid + 1] if mid + 1 < n else neg_inf

            if nums[mid] > left_val and nums[mid] > right_val:
                return mid

            if nums[mid] < left_val:
                r = mid - 1
            else:
                l = mid + 1

        return -1

 

직관적인 풀이는 nums를 loop 돌면서 nums[i]와 nums[i-1], nums[i+1]을 비교하는 방식이다.

 

하지만 문제의 마지막에 You must write an algorithm that runs in O(log n) time. 이라고 되어있으므로 단순히 O(n) = n의 loop를 도는게 아닌, 특정 방식의 탐색을 적용한 풀이를 원하는 것을 알 수 있다.

 

정렬도 안 됐으면서 무슨 탐색? 이라고 생각했지만, 문제가 원한다니까 무지성으로 왼쪽 오른쪽 조건을 바꿔가면서 binary search를 적용했다. 그게 통과가 된 후에 이게 왜 통과했지? 하고 생각을 해보니 탐색을 할 수 있는 이유가 있다.

 

nums 배열의 이웃하는 모든 값이 다르고, 배열의 양 끝은 -∞라고 할 때, nums[i]보다 nums[i-1]의 값이 크다면 i의 왼편에는 무조건 peak가 1개 이상 존재하게 된다.

그 반대의 경우 (nums[i]가 nums[i-1]보다 큰 경우) i의 오른편에 peak는 항상 1개 이상 존재한다.

따라서 binary search를 적용할 수 있다.

 

역시 몸이 고생하면 머리가 편하다.

728x90