按排序順序查詢 JavaScript 中的平方數
問題
我們需要編寫一個 JavaScript 函式,該函式接受一個以遞增順序排序的整數陣列 arr。
我們函式應該返回一個每個數字的平方構成的陣列,同樣按遞增順序排序。
例如,如果輸入函式的是
const arr = [-2, -1, 1, 3, 6, 8];
那麼輸出應該是
const output = [1, 1, 4, 9, 36, 64];
示例
程式碼如下:
const arr = [-2, -1, 1, 3, 6, 8]; const findSquares = (arr = []) => { const res = [] let left = 0 let right = arr.length - 1 while (left <= right) { const leftSquare = arr[left] * arr[left] const rightSquare = arr[right] * arr[right] if (leftSquare < rightSquare) { res.push(rightSquare) right -= 1 } else { res.push(leftSquare) left += 1 } } return res.reverse(); }; console.log(findSquares(arr));
輸出
控制檯中的輸出如下所示
[ 1, 1, 4, 9, 36, 64 ]
廣告