Find Peak Element
A peak element is an element, which is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1]
, the find a peak element and return its index.
The array may be contain multiple peaks, in this case return the index to any one of the peaks is fine.
May imagine num[-1] = num[n] = -∞
.
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.
Click to show spoilers.
Note:
Your solution should is in logarithmic complexity.
https://leetcode.com/problems/find-peak-element/
Suggest that the complexity of the requirements of the exponential level, I would like to not be able to ...
The original is preconceived, did not say to ask the highest peak, as long as the peak, any can orz.
I thought there were several top peaks, the output of which can be, the original requirements so casually, so really no problem.
So it can be two points, the midpoint is nothing more than four kinds of circumstances.
1. Midpoint is peak, direct output, call off.
2. Midpoint in an uphill, the peak must be on the right.
3. Midpoint in a downhill, the peak must be on the left.
4. Midpoint is Peak Valley, take the left and right can ...
1 /**2 * @param {number[]} nums3 * @return {number}4 */5 varFindpeakelement =function(nums) {6 varm = 0, n = nums.length-1;7 varMiddle, left, right;8 while(M <=N) {9Middle = parseint ((m + N)/2);Tenleft = nums[middle-1]? NUMS[MIDDLE-1]:-Infinity; Oneright = Nums[middle + 1]? Nums[middle + 1]:-Infinity; A if(Nums[middle] > left && nums[middle] >Right ) { - returnMiddle; -}Else if(Left < nums[middle]&& Nums[middle] <Right ) { them = middle + 1; -}Else{ -n = middle-1; - } + } - returnNUMS[M] > Nums[n]?Nums[m]: nums[n]; +};
[Leetcode] [JavaScript] Find Peak Element