0977. Squares of a Sorted Array
Method 1 #
- Time Complexity: O(n)
- Space Complexity: O(n)
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int l = 0;
int r = nums.size() - 1;
int index = nums.size() - 1;
vector<int> result(nums.size(), 1);
while(l <= r) {
int leftpower = nums[l] * nums[l];
int rightpower = nums[r] * nums[r];
if(leftpower > rightpower) {
result[index--] = leftpower;
l++;
} else {
result[index--] = rightpower;
r--;
}
}
return result;
}
};