LeetCode 977. Squares of a Sorted Array
考点 | 难度 |
---|---|
Sorting | Easy |
题目
Given an integer array nums
sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
思路
因为原数列是按照大小排序的,所以只需要比较首尾数字的平方。
答案
public int[] sortedSquares(int[] A) {
int n = A.length;
int[] result = new int[n];
int i = 0, j = n - 1;
for (int p = n - 1; p >= 0; p--) {
if (Math.abs(A[i]) > Math.abs(A[j])) {
result[p] = A[i] * A[i];
i++;
} else {
result[p] = A[j] * A[j];
j--;
}
}
return result;
}