Skip to content
Onsite

Find Peak Element

MediumP2Coding

A peak element is one that is strictly greater than both of its neighbours. The elements before the first and after the last are treated as negative infinity, so nums[0] is a peak when nums[0] > nums[1], and likewise for the last element.

Given nums where adjacent elements are never equal, return the index of a peak. A solution that runs in O(log n) is expected.

To keep the expected answer unique, every array in this judge contains exactly one peak. Your algorithm should not depend on that: on an array with several peaks, a binary search may return any of them.

Example 1

Input
nums = [1,2,3,1]
Output
2

Example 2

Input
nums = [5,4,3]
Output
0

Example 3

Input
nums = [1,2]
Output
1

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums[i] != nums[i + 1]
  • The judge's arrays contain exactly one peak

Hints

Run checks the 3 visible tests, Submit all 11.