在 JavaScript 中查找中心峰值数组的峰值
中心峰阵列
如果以下属性成立,我们将数组arr称为中心峰值数组-
arr.length>=3
存在一些具有0
arr[0]
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