在 JavaScript 中查找中心峰值数组的峰值
中心峰值数组
如果数组 arr 具有以下属性,我们称它为**中心峰值数组** −
arr.length >= 3
存在某个 i 使 0 < i < arr.length - 1,并且
arr[0] < arr[1] < ... arr[i-1] < arr[i]
arr[i] > arr[i+1] > ... > arr[arr.length - 1]
问题
我们需要编写一个 JavaScript 函数,它将接收一个数字数组 arr,作为第一个也是唯一的参数。
输入数组是一个中心峰值数组。我们的函数应该返回此中心峰值数组的峰值索引。
例如,如果输入函数为
输入
const arr = [4, 6, 8, 12, 15, 11, 7, 4, 1];
输出
const output = 4;
输出说明
因为索引 4(15)处的元素是该数组的峰值元素。
示例
以下是代码 −
const arr = [4, 6, 8, 12, 15, 11, 7, 4, 1];
const findPeak = (arr = []) => {
if(arr.length < 3) {
return -1
}
const helper = (low, high) => {
if(low > high) {
return -1
}
const middle = Math.floor((low + high) / 2)
if(arr[middle] <= arr[middle + 1]) {
return helper(middle + 1, high)
}
if(arr[middle] <= arr[middle - 1]) {
return helper(low, middle - 1)
}
return middle
}
return helper(0, arr.length - 1)
};
console.log(findPeak(arr));输出
4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP