在 JavaScript 中按排序顺序查找平方数

javascriptweb developmentfront end technology

问题

我们需要编写一个 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 ]

相关文章