Leetcode-find Peak Element

Source: Internet
Author: User

Find Peak Element

2015.1.23 14:28

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.

Note:

Your solution should is in logarithmic complexity.

Solution:

The requirement of O (log (n)) time really Got me this time (x_x) | |

I Haven ' t come by any solution with binary search. Here's one I sought out on the Internet, but judging from the run time, it seems worse to use binary search than linear s Earch. So what's the catch then?

Http://www.cnblogs.com/ganganloveu/p/4147655.html

Maybe it ' s just unreasonable to apply binary search on unordered sequences. You don ' t know for sure which path to go next, how would do it binary then? Well, I ' d say the O (log (n)) requirement is a bit unsound.

Accepted Code:

1 //1CE, 2WA, 1AC, how to achieve logn with unordered data?2 classSolution {3  Public:4     intFindpeakelement (Constvector<int> &num) {5         intn = (int) num.size ();6 7         if(n = =1) {8             return 0;9         }Ten          One         if(num[0] > num[1]) { A             return 0; -         } -          the         if(Num[n-1] > Num[n-2]) { -             returnN-1; -         } -          +         inti; -          for(i =1; I < n-1; ++i) { +             if(Num[i] > Num[i-1] && Num[i] > num[i +1]) { A                 returni; at             } -         } -     } -};

Leetcode-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.