[Leetcode] Find Peak Element to find the peaks of an array

Source: Internet
Author: User

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

The problem is to find a peak of the array, the peak can be a local maximum value, here to traverse the entire array to find the maximum value will definitely appear time Limit exceeded, we have to consider using similar to the binary lookup method to shorten the times, because just need to locate any one of the peaks, Then we determine the two points after the middle of the binary after the element, and immediately after the element compared to the size, if greater than, the peak is in front, if less than in the back. This will allow you to find a peak with the following code:

classSolution { Public:    intFindpeakelement (Constvector<int> &num) {        intleft =0; intright = Num.size ()-1;  while(Left <=Right ) {            if(left = right)returnRight ; intMiddle = (left + right)/2; if(Num[middle] < Num[middle +1]) left = middle +1; Elseright =Middle; }    }};

[Leetcode] Find peak Element to find the peaks of an array

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.