[Leetcode] [JavaScript] Find Peak Element

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.