原题网址:https://leetcode.com/problems/find-peak-element/
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.
Note:
Your solution should be in logarithmic complexity.
方法一:全局扫描。
public class Solution {
public int findPeakElement(int[] nums) {
if (nums == null || nums.length==0) return -1;
if (nums.length==1) return 0;
if (nums[0] > nums[1]) return 0;
if (nums[nums.length-2] < nums[nums.length-1]) return nums.length-1;
for(int i=1; i<nums.length-1; i++) {
if (nums[i-1] < nums[i] && nums[i] > nums[i+1]) return i;
}
return -1;
}
}
方法二:二分法。
public class Solution {
public int findPeakElement(int[] nums) {
int i=0, j=nums.length-1;
while (i<j) {
int m = (i+j)/2;
if (nums[m] > nums[m+1]) j=m; else i=m+1;
}
return i;
}
}

本文介绍了一种在数组中寻找峰值元素的方法。峰值元素是指大于其邻居的元素。文章提供了两种解决方案:一种是通过全局扫描的方式找到峰值,另一种是采用二分法进行高效查找。特别强调了二分法解决方案的时间复杂度为O(log n)。
&spm=1001.2101.3001.5002&articleId=51487108&d=1&t=3&u=2a3e85e1ce9945d69e5e04ea668e8d47)
3100

被折叠的 条评论
为什么被折叠?



