[LeetCode] Squares of a Sorted Array

977. Squares of a Sorted Array

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?

  • Time : O(n)
  • Space : O(1) (except result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
vector<int> res;
int l = 0, r = nums.size() - 1;
while(l <= r) {
if(abs(nums[l]) < abs(nums[r])) {
res.push_back(nums[l] * nums[l++]);
} else {
res.push_back(nums[r] * nums[r--]);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/10/PS/LeetCode/squares-of-a-sorted-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.