162. Find Peak Element

Hill K·2022년 8월 20일
0

Algorithm

목록 보기
5/11

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.

조건

1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
nums[i] != nums[i + 1] for all valid i.

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

이진탐색 사용

class Solution:
    def findPeakElement(self, nums: List[int]) -> int:

        return nums.index((max(nums)))

이렇게 사용하여도 결과는 같게 나오며 시간도 비슷하게 나온다.

profile
안녕하세요

0개의 댓글