首页 > 其他 > 详细

LeetCode - Find Peak Element

时间:2015-01-23 16:05:14      阅读:375      评论:0      收藏:0      [点我收藏+]

Find Peak Element

2015.1.23 14:28

A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that 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 be 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 is one I sought out on the Internet, but judging from the run time, it seems worse to use binary search than linear search. 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 you make 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 class Solution {
 3 public:
 4     int findPeakElement(const vector<int> &num) {
 5         int n = (int)num.size();
 6 
 7         if (n == 1) {
 8             return 0;
 9         }
10         
11         if (num[0] > num[1]) {
12             return 0;
13         }
14         
15         if (num[n - 1] > num[n - 2]) {
16             return n - 1;
17         }
18         
19         int i;
20         for (i = 1; i < n - 1; ++i) {
21             if (num[i] > num[i - 1] && num[i] > num[i + 1]) {
22                 return i;
23             }
24         }
25     }
26 };

 

LeetCode - Find Peak Element

原文:http://www.cnblogs.com/zhuli19901106/p/4244171.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!