双指针法
class Solution {
public int[] sortedSquares(int[] nums) {
/**
* 先求出所有元素的平方,然后从两端双指针遍历
* 两端的元素总是最大的,逆序插入新的数组
*/
for (int i = 0; i < nums.length; i++) {
nums[i] = nums[i] * nums[i];
}
int left = 0;
int right = nums.length - 1;
int[] arr = new int[nums.length];
for (int i = arr.length - 1; i >= 0; i--) {
if (nums[left] >= nums[right]){
arr[i] = nums[left++];
}
else {
arr[i] = nums[right--];
}
}
return arr;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
优化1——在求平方的同时排序
class Solution {
public int[] sortedSquares(int[] nums) {
/**
* 先比较出平方的大小,然后直接记录大的数值,在一个循环中进行
*/
int left = 0;
int right = nums.length - 1;
int[] arr = new int[nums.length];
for (int i = arr.length - 1; i >= 0; i--) {
if (nums[left] * nums[left] >= nums[right] * nums[right]){
arr[i] = nums[left] * nums[left++];
}
else {
arr[i] = nums[right] * nums[right--];
}
}
return arr;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/squares-of-a-sorted-array/