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 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)