# Question

Formatted question description: https://leetcode.ca/all/162.html

 162. Find Peak Element

A peak element is an element that is greater than its neighbors.

Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that nums[-1] = nums[n] = -∞.

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: 1 or 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.

Note:
Your solution should be in logarithmic complexity.

@tag-array


# Algorithm

If you traverse the entire array to find the maximum value here, Time Limit Exceeded will definitely appear, but the title says that this peak can be a local maximum, so we only need to find the first local peak.

The so-called peak value is a number that is larger than the surrounding two numbers, so you only need to compare it with the surrounding two numbers.

• Since you want to compare with the left and right numbers, you have to consider the problem of out-of-bounds. The title gives nums[-1] = nums[n] = -∞, then add these two integer minimums directly to the array, and then Traverse from the second number to the penultimate number, so that there is no possibility of crossing the boundary.
• Since the question says that the peak must exist, there is a very important corner case that we should pay attention to, that is, when there is only one number in the original array, and it is the minimum value of an integer, if we have to add numbers at the beginning and end, A horizontal line will be formed, and there will be no peak value, so we directly judge the situation that there is only one number in the array at the beginning

Then, based on idea above, you can omit the step of padding the first and last values, and you can traverse from the second number to the next,

• If the second number is smaller than the first number, it means that the first number is a local peak at this time;
• Otherwise, it will continue to traverse back, and now it is an increasing trend. If a certain number is less than the previous number at this time, it means that the previous number is a local peak, just return to the position.
• If the loop ends, it means that the original array is an increasing array, just return to the last position

Java