跳至主要內容

对排序后的数组进行平方


对排序后的数组进行平方

题目

给定一个已排序的数组,创建一个新数组,其中包含输入数组中所有按排序顺序排列的数字的平方。

示例1:

输入:[-2, -1, 0, 2, 3]
输出:[0, 1, 4, 4, 9]
解释:元素平方后依然有序

示例2:

输入:[-3, -1, 0, 1, 2]
输出:[0, 1, 1, 4, 9]
解释:元素平方后依然有序

解答1:

class SortedArraySquares {

  public static int[] makeSquares(int[] arr) {
    int n = arr.length;
    int[] squares = new int[n];
    int highestSquareIdx = n - 1;
    int left = 0, right = arr.length - 1;
    while (left <= right) {
      int leftSquare = arr[left] * arr[left];
      int rightSquare = arr[right] * arr[right];
      if (leftSquare > rightSquare) {
        squares[highestSquareIdx--] = leftSquare;
        left++;
      } else {
        squares[highestSquareIdx--] = rightSquare;
        right--;
      }
    }
    return squares;
  }

  public static void main(String[] args) {

    int[] result = SortedArraySquares.makeSquares(new int[] { -2, -1, 0, 2, 3 });
    for (int num : result)
      System.out.print(num + " ");
    System.out.println();

    result = SortedArraySquares.makeSquares(new int[] { -3, -1, 0, 1, 2 });
    for (int num : result)
      System.out.print(num + " ");
    System.out.println();
  }
}
上次编辑于:
贡献者: Neil