1. 题目原址
https://leetcode.com/problems/squares-of-a-sorted-array/
2. 题目描述
3. 题目大意
给定一个有序数组,数组中存在负数,要求将数组中的元素平方后保证数组依旧有序。
4. 解题思路
定义一个变量 k 作为数组下标,一个变量i前往后遍历,另一个变量j从后往前遍历。
5. AC代码
class Solution {
public int[] sortedSquares(int[] A) {
int n = A.length;
int[] ret = new int[n];
int i = 0, j = n - 1,k = n - 1;
while(i <= j) {
ret[k --] = A[i] * A[i] >= A[j] * A[j] ? A[i] * A[i ++] : A[j] * A[j--];
}
return ret;
}
}