151 DSA Problem journey
Squares of sorted array
Published
•1 min read
G
Experienced Full Stack Developer with proficiency in comprehensive coding skills, adept at crafting end-to-end solutions.
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example:
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].
Solution:
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums)
{
int n=nums.size();
vector<int>ans(n);
for(int i=0;i<n;i++)
{
ans[i]=nums[i]*nums[i];
}
sort(ans.begin(),ans.end());
return ans;
}
};
Explantion:
.)Obtain the size of the given array and store it in a variable n.
.)Declare a vector named ans with a size of n.
.)Iterate through each element in the array using a loop with the index i ranging from 0 to n-1.
.)Square each element and store it in the ans vector at the corresponding index.
.)Sort the ans vector.
.)Return the sorted ans vector.
If any one have better solution so please comment :)




