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.
在数组中找到一个数,该数的值大于与其相邻的左右两个元素的值。数组两边没有数的部分可以认为是无穷小。
解题思路:按照题意,nums[0]是大于左边的不存在的那个元素的,nums[nums.length-1]也是大于右边那个不存在的元素。找到第一个破坏升序的元素,返回其上一个元素的下标就可以了。如果一直是升序,则返回最后一个元素的下标
public class Solution {
public int findPeakElement(int[] nums) {
for (int i = 0; i < nums.length -1; i++) {
if (nums[i] > nums[i+1]) {
return i;
}
}
return nums.length - 1;
}
}
该解法的复杂度为O(n),比较次数n。
还可以用二分查找。比较次数为O(logN),懒得写。先这样吧