[Leetcode]Find Peak Element
来源:互联网 发布:centos 删除 rm 编辑:程序博客网 时间:2024/06/08 11:15
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.
click to show spoilers.
Note:
Your solution should be in logarithmic complexity.
class Solution {public: /*algorithm : linear search time O(n) space O(1) */ int findPeakElement(vector<int>& nums) { for(int i = 0;i < nums.size();i++){ bool prev = i==0?true:nums[i] > nums[i-1]; bool next = i+1==nums.size()?true:nums[i]>nums[i+1]; if(prev&&next)return i; } return -1; }};
class Solution {public: /*algorithm : linear search time O(logn) space O(1) */ int findPeakElement(vector<int>& nums) {//[0,1,2,3,1] bool prev,next; int l = 0,r = nums.size(); while(l < r){ int m = l + (r-l)/2; prev = m == 0?true:nums[m] > nums[m-1]; next = m+1==nums.size()?true:nums[m] > nums[m+1]; if(prev&&next)return m; else if(prev)l = m+1; else r = m; //becasue [l,r),not [l,r] } return -1; }};
0 0
- [LeetCode] Find Peak Element
- Leetcode:Find Peak Element
- LeetCode Find Peak Element
- leetcode: Find Peak Element
- leetcode:Find Peak Element
- LeetCode Find Peak Element
- Find Peak Element --leetcode
- Leetcode Find Peak Element
- [LeetCode] Find Peak Element
- Leetcode Find Peak Element
- Leetcode: Find Peak Element
- 【leetcode】Find Peak Element
- leetcode:Find Peak Element
- 【Leetcode】Find Peak Element
- LeetCode:Find Peak Element
- LeetCode:Find Peak Element
- [LeetCode] Find Peak Element
- LeetCode Find Peak Element
- OpenGL教程翻译 第二十三课 阴影贴图(一)
- 网页常用JavaScript代码
- 关于On Error Resume Next与On Error Goto 0
- uva 10820 约束个数
- 使用层序遍历序列化和反序列化二叉树
- [Leetcode]Find Peak Element
- OpenGL教程翻译 第二十四课 阴影贴图(二)
- 第一个iPhone app
- Java入门01
- 责任链模式模拟servlet过滤器
- 行编辑器
- php获取ip地址所在的地理位置的实现
- JS对象入门
- 初入JAVAMAIL之如何能运用其文件笔记