LintCode Find Peak Element(查找峰值)
2016-06-21 01:38
323 查看
原题网址:http://www.lintcode.com/en/problem/find-peak-element/
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:
Find a peak element in this array. Return the index of the peak.
Notice
The array may contains multiple peeks, find any of them.
Example
Given
Return index
is number 2) or
方法:二分法。答案可能不唯一,只需要得到一个即可。
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.
Example
Given
[1, 2, 1, 3, 4, 5, 7, 6]
Return index
1(which
is number 2) or
6(which is number 7)
方法:二分法。答案可能不唯一,只需要得到一个即可。
class Solution { /** * @param A: An integers array. * @return: return any of peek positions. */ public int findPeak(int[] A) { // write your code here int i = 1, j = A.length - 2; while (i <= j) { int m = (i + j) / 2; if (A[m - 1] < A[m] && A[m] > A[m + 1]) return m; if (A[m - 1] < A[m]) i = m + 1; else j = m - 1; } return i; } }
相关文章推荐
- LintCode Majority Number iii
- LintCode-最大数
- lintCode Intersection of Two Arrays II
- Subtree
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode --find-the-missing-number(寻找缺失的数)
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- lintcode之不同子序列数 + 序列II
- lintcode之快速幂
- lintcode删除排序数组中的重复数字 II
- lintcode之数组划分
- leetcode之三数之和 II
- lintcode之 数组剔除元素后的乘积
- lintcode之 合并排序数组 II
- lintcode 之子数组之和
- lintcode之最长公共前缀
- lintcode 之 最长公共子串
- 中位数 21% 通过 给定一个未排序的整数数组,找到其中位数。 中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数