class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
vector<int> sorted(nums.size());
int sortedIndex = 0;
int leftIndex, rightIndex;
int i = 0;
while (i < nums.size() && nums[i] < 0) i++; // Searching the first element in nums that
rightIndex = i; // is not negative.
leftIndex = i - 1;
while (leftIndex >=0 || rightIndex < nums.size()) { // Starting from the first not negative
if (leftIndex >=0 && rightIndex < nums.size()) { // number; rightIndex goes right; left
int a = nums[leftIndex] * nums[leftIndex]; // index goes left; counting the squares of
int b = nums[rightIndex] * nums[rightIndex]; // nums[rightIndex] and nums[leftIndex] and
if (b <=a) { // putting the smaller number into the
sorted[sortedIndex] = b; // result array 'sorted'.
sortedIndex++;
rightIndex++;
}
else {
sorted[sortedIndex] = a;
sortedIndex++;
leftIndex--;
}
} else if (leftIndex < 0) { // Handling the case when leftIndex reached
int b = nums[rightIndex] * nums[rightIndex]; // the beginning of the array 'nums'.
sorted[sortedIndex] = b;
sortedIndex++;
rightIndex++;
} else { // Handling the case when rightIndex reached
int a = nums[leftIndex] * nums[leftIndex]; // the end of the array 'nums'.
sorted[sortedIndex] = a;
sortedIndex++;
leftIndex--;
}
}
return sorted;
}
};