1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
let findThePeak = (arr, i, j) => { let current = parseInt((i + j) / 2)
if (arr[current] < arr[current + 1]) return findThePeak(arr, current, j) else if (arr[current] < arr[current - 1]) return findThePeak(arr, i, current) else return arr[current] }
let findThePeak2 = (arr, start, end) => { let current = parseInt((start + end) / 2) let rowMax = findThePeak(arr[current], 0, arr[current].length)
let i = arr[current] .map((i, index) => i === rowMax && index) .filter((i) => i !== false)[0]
if (current - 1 >= 0 && arr[current][i] < arr[current - 1][i]) { return findThePeak2(arr, start, current) } else if (current < end - 1 && arr[current][i] < arr[current + 1][i]) { return findThePeak2(arr, current, end) } else { return rowMax } }
let arr = [5, 4, 3, 2, 4, 5, 6] let arr2 = [ [6, 3, 8], [3, 2, 1], [4, 6, 1], ]
console.log(findThePeak(arr, 0, arr.length)) console.log(findThePeak2(arr2, 0, arr2.length))
|