在 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 ]

猜你喜欢