[LintCode] Find Peak Element 求数组的峰值
2024-09-28 05:30:20
There is an integer array which has the following features:
- The numbers in adjacent positions are different.
- A[0] < A[1] && A[A.length - 2] > A[A.length - 1].
We define a position P is a peek if:
A[P] > A[P-1] && A[P] > A[P+1]
Find a peak element in this array. Return the index of the peak.
Notice
The array may contains multiple peeks, find any of them.
Have you met this question in a real interview?
Example
Given [1, 2, 1, 3, 4, 5, 7, 6]
Return index 1
(which is number 2) or 6
(which is number 7)
Challenge
Time complexity O(logN)
LeetCode上的原题,请参见我之前的博客Find Peak Element。
解法一:
class Solution {
public:
/**
* @param A: An integers array.
* @return: return any of peek positions.
*/
int findPeak(vector<int> A) {
int left = , right = A.size() - ;
while (left < right) {
int mid = left + (right - left) / ;
if (A[mid] < A[mid + ]) left = mid + ;
else right = mid;
}
return right;
}
};
解法二:
class Solution {
public:
/**
* @param A: An integers array.
* @return: return any of peek positions.
*/
int findPeak(vector<int> A) {
for (int i = ; i < A.size(); ++i) {
if (A[i] < A[i - ]) return i - ;
}
return A.size() - ;
}
};
最新文章
- 使用CocoaPods过程中 Unable to find a specification for
- Struts2_ValueStack,OGNL详解(转)
- centos BIND服务基础及域主服务器配置
- Hession矩阵与牛顿迭代法
- android 为TextView添加边框
- ajax提交到后台是中文乱码
- The area 积分积分
- python基础1之 由来、种类、优缺点、安装环境
- 1个汉字在UTF-8编码占3个字节
- JMeter&#160;逻辑控制之While循环控制器(While&#160;Controller)
- 软件常用设置(VC, eclipse ,nodejs)---自己备用
- python django简单的登陆实现
- scikit-FEM-例1-求解Possion边值问题
- mkubimage-mlc2: error while loading shared libraries: liblzo2.so.2: cannot open shared object file: No such file or directory
- elasticSearch6源码分析(1)启动过程
- find-k-pairs-with-smallest-sums
- Esper简介
- python可变容器类型做函数参数的坑
- 7. I/O复用
- c++输出保留固定小数位数