977. Squares of a Sorted Array

Solution

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int l = 0;
        int r = nums.size() - 1;
        vector<int> res(nums.size());
        
        int i = r;
        while (l <= r) {
            int ls = nums[l] * nums[l];
            int rs = nums[r] * nums[r];
            
            if (rs > ls) {
                res[i] = rs;
                r--;
            } else {
                res[i] = ls;
                l++;
            }
            i--;
        }
        
        return res;
    }
};

Complexity

  • Time Complexity: O(N), where N is the size of nums.
  • Space Complexity: O(N), where N is the size of nums.

All Solutions