题解 | 寻找峰值
寻找峰值
https://www.nowcoder.com/practice/fcf87540c4f347bcb4cf720b5b350c76
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* [2,4,1,2,7,8,4] => 1
* [1,2,3,1] => 2
* [1,2,3,4,5] => -1
*
* @param nums int整型一维数组
* @return int整型
*/
function findPeakElement(nums) {
if (nums.length === 1) return 0;
// write code here
let index = 0;
while (index <= nums.length - 1) {
let index_left = index - 1;
let index_right = index + 1;
const is_big_left = nums[index_left]
? nums[index] > nums[index_left]
: true;
const is_big_right = nums[index_right]
? nums[index] > nums[index_right]
: true;
if (is_big_left && is_big_right) {
return index;
} else {
index++;
}
}
return -1;
}
module.exports = {
findPeakElement: findPeakElement,
};

查看12道真题和解析