LeetCode/977. 有序数组的平方

977. 有序数组的平方

给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。

示例1:

1
2
输入:[-4,-1,0,3,10]
输出:[0,1,9,16,100]

示例2:

1
2
输入:[-7,-3,2,3,11]
输出:[4,9,9,49,121]

提示:

  1. 1 <= A.length <= 10000
  2. -10000 <= A[i] <= 10000
  3. A 已按非递减顺序排序。

来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

题解:

本题利用双指针,一个指向头,一个指向尾,比较两数平方的大小,然后倒序插入新建的数组当中。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int[] sortedSquares(int[] A) {
int[] result = new int[A.length];
int index = A.length - 1;
int left = 0, right = A.length - 1;
while (left <= right) {
if (A[left] * A[left] > A[right] * A[right]) {
result[index--] = A[left] * A[left];
left++;
} else {
result[index--] = A[right] * A[right];
right--;
}
}
return result;
}
}

Comments