随笔- 509  文章- 0  评论- 151  阅读- 22万 

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.

Solution1:

  Here is the O(n) solution.

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 };
复制代码

Solution2:

  I came up with the log(n) solution at last. See the code below.

Accepted code:

复制代码
 1 // 2WA, 1AC, the O(log(n)) solution
 2 class Solution {
 3 public:
 4     int findPeakElement(vector<int> &nums) {
 5         int n = nums.size();
 6         if (n == 1) {
 7             return 0;
 8         }
 9         
10         int ll, rr, mm;
11         
12         ll = 0;
13         rr = n - 1;
14         while (rr - ll >= 2) {
15             mm = (ll + rr) / 2;
16             if (nums[mm] > nums[mm - 1] && nums[mm] > nums[mm + 1]) {
17                 return mm;
18             } else if (nums[mm - 1] < nums[mm]) {
19                 ll = mm;
20             } else {
21                 rr = mm;
22             }
23         }
24         if (nums[0] > nums[1]) {
25             return 0;
26         } else {
27             return n - 1;
28         }
29     }
30 };
复制代码

 

 posted on   zhuli19901106  阅读(250)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示