码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Find Peak Element

时间:2015-01-23 16:07:13      阅读:172      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!