@AlgoPrep - 2 - Array - Square Of Sorted Array

karan arorakaran arora
1 min read
    vector<int> sortedSquares(vector<int>& nums) {
        int n = nums.size();
        int start=0;
        int end=n-1;

        vector <int> res(n);
        int pos = n-1;

        while(start <= end){
            if(abs(nums[start]) < abs(nums[end])) {
                res[pos--] = nums[end] * nums[end];
                end--;
            } else{
                res[pos--] = nums[start] * nums[start];
                start++;
            }
        }

        return res;
    }
class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int n=nums.size();
        for(int i=0;i<n;i++){
            nums[i]=pow(nums[i],2);
        }
         sort(nums.begin(),nums.end());
        return nums;
    }
};
0
Subscribe to my newsletter

Read articles from karan arora directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

karan arora
karan arora