[AlgoExpert] Sorted Squared Array

Sorted Squared Array

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <vector>
using namespace std;

vector<int> sortedSquaredArray(vector<int> array) {
auto mi = min_element(begin(array), end(array), [](int a, int b) {
return abs(a) < abs(b);
}) - begin(array);
int l = mi, r = l + 1, n = array.size();
vector<int> res;
while(l >= 0 and r < n) {
if(abs(array[l]) > abs(array[r])) {
res.push_back(array[r] * array[r]); r++;
} else {
res.push_back(array[l] * array[l]); l--;
}
}
while(l >= 0) {
res.push_back(array[l] * array[l]); l--;
}
while(r < n) {
res.push_back(array[r] * array[r]); r++;
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/sorted-squared-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.