977. 有序数组的平方

image.png

双指针法

执行用时:3 ms, 在所有 Java 提交中击败了22.44% 的用户 内存消耗:39.9 MB, 在所有 Java 提交中击败了90.37% 的用户

  1. class Solution {
  2. public int[] sortedSquares(int[] nums) {
  3. int l = 0, r = nums.length - 1;
  4. int[] res = new int[nums.length];
  5. for (int i = nums.length - 1; i >= 0; i--) {
  6. if (Math.abs(nums[l]) < Math.abs(nums[r])) {
  7. res[i] = nums[r] * nums[r];
  8. r --;
  9. } else {
  10. res[i] = nums[l] * nums[l];
  11. l ++;
  12. }
  13. }
  14. return res;
  15. }
  16. }