Leetcode[array]: Find Peak Element

Source: Internet
Author: User

a peak element is a element is greater than its neighbors.
given an input array where num[i]≠num[i+1], the find a peak element and return its index.
you may imagine this num[-1] = num[n] =-∞.
for example, in array [1, 2, 3, 1], 3 is a peak eleme NT and your function should return the index number 2.
note:
your solution should is in logarithmic Complexity.

This topic requires a time complexity of O (log (N)), can use binary lookup to do, but the update search interval here is not quite the same: if the previous step to mid is uphill and mid's next is downhill, then mid is the peak; if the previous and the last steps of mid are uphill, Then the top of the mountain must be in the second half of the range; if the previous and next steps of mid are downhill, the peak must be in the first half. In addition, boundary issues need to be addressed.

My C + + code is implemented as follows:

int findpeakelement (const vector<int> &num) {    int low = 0, high = num.size ()-1;    while (low <= high) {        int mid  = (low + high) >> 1;        BOOL Isuphillforward = (Mid = = 0? True:num[mid] > Num[mid-1]);        BOOL Isuphillafter = (Mid = = Num.size ()-1? false:num[mid + 1] > Num[mid]);        if (Isuphillforward &&!isuphillafter) return mid;        else if (Isuphillforward && isuphillafter) Low = mid + 1;        else high = mid-1;    }    return low;}


Leetcode[array]: Find Peak Element

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.