比较直观的解法
var sortedSquares = function(A) {
return A.sort((a, b)=>{
return Math.abs(a) -Math.abs(b)
}).map(function(el){
return el * el
})
};
另一个,从左右两端开始比较,可能是-123与124比较,然后是-123与122
var sortedSquares = function(A) {
let left = 0;
let right = A.length - 1;
const result = new Array(A.length);
let index = A.length - 1;
while (left <= right) {
const leftSquare = A[left] * A[left];
const rightSquare = A[right] * A[right];
if (leftSquare > rightSquare) {
result[index] = leftSquare;
left++;
} else {
result[index] = rightSquare;
right--;
}
index--;
}
return result;
};