977. Squares of a Sorted Array (Leetcode)

PHOTO EMBED

Tue Oct 05 2021 11:18:54 GMT+0000 (UTC)

Saved by @Sakshamkashyap7 #c++

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        vector<int>ans(nums.size());
        int first = 0, second = nums.size() - 1;
        for(int ind = nums.size() - 1; ind >= 0; ind--)  {
            if(abs(nums[first]) < nums[second]) 
                ans[ind] = nums[second] * nums[second--];
            else    ans[ind] = nums[first] * nums[first++];
        }
        return ans;
        
    }
}


//2nd approch
class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        vector<int>ans;
        int first = 0,second = 0;
        while(first<nums.size() && nums[first]<0  ) {
            first++;
        }
        second = first;
        first -= 1;
        while(first>=0 && second<nums.size())   {
            if(abs(nums[first] * nums[first]) < (nums[second] * nums[second]))  {
                ans.push_back(nums[first] * nums[first]);
                first--;
            }
            else {
                ans.push_back(nums[second] * nums[second]);
                second++;
            }
        }
        while(first>=0) {
            ans.push_back(nums[first] * nums[first]);
            first--;
        }
        while(second<nums.size())   {
            ans.push_back(nums[second] * nums[second]);
            second++;
        }
        return ans;

    }
};
content_copyCOPY

Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100].

https://leetcode.com/problems/squares-of-a-sorted-array/