问题:数组
A peak element is an element that is greater than its neighbors.spa
Given an input array where num[i] ≠ num[i+1]
, find a peak element and return its index.code
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.ip
You may imagine that num[-1] = num[n] = -∞
.element
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.input
Note:it
Your solution should be in logarithmic complexity.io
解决:function
① 自左至右遍历数组,若是某元素比它左边和右边的元素大,则该元素必为顶点。返回找到的第一个顶点便可。class
class Solution { //1ms
public int findPeakElement(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}else if (nums.length == 1) {
return 0;
}else if (nums[0] > nums[1]) {
return 0;
}else if (nums[nums.length - 1] > nums[nums.length - 2]) {
return nums.length - 1;
}
for (int i = 1;i < nums.length - 1 ;i ++ ) {
if (nums[i - 1] <= nums[i] && nums[i + 1] <= nums[i]) {
return i;
}
}
return -1;
}
}
② 这种找Peak Element的首先想到的是binary search, 由于有更优的时间复杂度,不然brute force O(n)
的方法太直接了。
这个方法利用了题目中的以下性质:
1)最左边的元素,它“更左边”的元素比它小(负无穷),咱们认为它是一个增加的方向
2)最右边的元素,它“更右边”的元素比它小(也是负无穷),咱们认为它是一个降低的方向
根据这两点咱们能够判断:最左边和最右边的元素围成的区域内,必有至少一个顶点
如今咱们找到中点 nums[mid],将它与 nums[mid + 1] 做比较,若是前者较小,则方向是增加,与最左边的元素是一致的,就把左边界挪到mid+1的位置;不然与最右边的元素一致,将右边界挪到mid的位置。
这个方法的原理就是当左边界方向为“增加”,右边界方向为“降低”时,两者围出的区域必有一个顶点。
binary search的方法就是比较当前element与邻居,至于左邻居仍是右邻居均可以,只要一致就行。不断缩小范围,最后锁定peak element.time: O(logn), space: O(1).
class Solution {//0ms public int findPeakElement(int[] nums) { int left = 0; int right = nums.length - 1; while(left < right){ int mid = (right - left) / 2 + left; if (nums[mid] < nums[mid + 1]){ left = mid + 1; }else{ right = mid; } } return left; } }