977. Squares of a Sorted Array
前往題目
想法
- 直接一個一個平方,然後用
comparator
的方式排進新的array
- 中間一定是最小的,
2 pointers
應該可以用
思路
2 pointers
,大的先加入答案,直到最小值- 反向加入,回傳時就不用額外的操作反轉
array
Code
class Solution {
public int[] sortedSquares(int[] nums) {
int[] res = new int[nums.length];
int l = 0, r = nums.length - 1;
int p = nums.length - 1; // Pointer for res, start from the end
while (l <= r) {
// From biggest to smallest
if (Math.abs(nums[l]) > Math.abs(nums[r])) {
res[p] = nums[l] * nums[l];
++l;
} else {
res[p] = nums[r] * nums[r];
--r;
}
// back to the front
--p;
}
return res;
}
}
977. Squares of a Sorted Array
https://f88083.github.io/2024/01/22/977-Squares-of-a-Sorted-Array-Easy/