题解 | #寻找峰值#
寻找峰值
https://www.nowcoder.com/practice/fcf87540c4f347bcb4cf720b5b350c76
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
public int findPeakElement (int[] nums) {
// write code here
//nums[-1] = nums[n] = -无穷大
// nums[i] != nums[i + 1]
int len = nums.length;
if (len == 1) return 0;
//排除开头俩和结尾俩
if (nums[0] > nums[1]) return 0;
if (nums[len - 2] < nums[len - 1]) return len - 1;
//锁定范围为[1, len-2]
int ans = 1;
while (ans <= len - 2) {
int aa = nums[ans - 1];
int bb = nums[ans];
int cc = nums[ans + 1];
if (aa < bb) {
if (bb > cc) {
return ans;
} else {
ans++;
}
} else {
if (bb > cc) {
ans += 2;
} else {
ans++;
}
}
}
return -1;
}
}
SHEIN希音公司福利 356人发布
