-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSquaresofSortedArray.cpp
More file actions
51 lines (48 loc) · 1.23 KB
/
SquaresofSortedArray.cpp
File metadata and controls
51 lines (48 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// #include <iostream>
// #include <vector>
// #include <algorithm>
// class Solution
// {
// public:
// vector<int> sortedSquares(vector<int> &nums)
// {
// vector<int> result;
// for (int i = 0; i < nums.size(); ++i)
// {
// result.push_back(nums[i] * nums[i]);
// }
// sort(result.begin(), result.end());
// return result;
// }
// };
//* optimized version time : O(n log n) , space : O(n) or O (log n) , no built in sort (2 pointers)
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
vector<int> sortedSquares(vector<int> &nums)
{
int ptr1 = 0;
int ptr2 = nums.size() - 1;
int idx_to_place_elem = nums.size() - 1;
vector<int> result(nums.size());
while (ptr1 <= ptr2)
{
if (abs(nums[ptr2]) > abs(nums[ptr1]))
{
result[idx_to_place_elem] = nums[ptr2] * nums[ptr2];
ptr2--;
idx_to_place_elem--;
}
else
{
result[idx_to_place_elem] = nums[ptr1] * nums[ptr1];
ptr1++;
idx_to_place_elem--;
}
}
return result;
}
};