[text] 977. Squares of a Sorted Array

Viewer

copyrawdownloadembedprintName: 977. Squares of a Sorted Array
  1. class Solution {
  2.     public int[] sortedSquares(int[] nums) {    
  3.         //time complexity  O(n)
  4.         //space complexity O(n)
  5.         
  6.         int n = nums.length;
  7.         int left = 0;
  8.         int right = n -1;
  9.         int[] result = new int[n];
  10.         
  11.         for (int i = n - 1; i>=0; i--) {
  12.             
  13.             int square;
  14.             if (Math.abs(nums[left]) < Math.abs(nums[right])) {
  15.                 square = nums[right];
  16.                 right--;
  17.             }else {
  18.                 square = nums[left];
  19.                 left++;
  20.             }
  21.             result[i] = square * square;
  22.             
  23.         }
  24.         return result;
  25.     }
  26. }

Editor

You can edit this paste and save as new:


File Description
  • 977. Squares of a Sorted Array
  • Paste Code
  • 05 May-2021
  • 679 Bytes
You can Share it: