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

 

Find Peak Element - LeetCode

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 m

leetcode.com

 

문제

peek 은 양 옆의 수보다 큰 수 

peek을 찾는 문제 

배열의 처음-1 과 마지막+1 자리는 가장 작은 수 되어 있어서 처음이나 마지막 원소가 그 전 원소보다 크면 peek이다

 

you must write an algorithm that runs in O(log n) time.

> 이진 탐색으로 풀어라

 

 

코드 

 

public class L162 {
    public int findPeakElement(int[] nums) {
        int left = 0;
        int right = nums.length - 1;

        while (left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] < nums[mid + 1]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }

        return left;
    }
}

+ Recent posts