-
Notifications
You must be signed in to change notification settings - Fork 0
/
sortedSquaredArray.cpp
51 lines (47 loc) · 1.02 KB
/
sortedSquaredArray.cpp
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
// Q3: Given an integer array 'a' sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
void sortedSquaredArray(vector<int> &v)
{
int leftptr = 0;
int rightptr = v.size() - 1;
vector<int> ansV;
while (leftptr <= rightptr)
{
if (abs(v[leftptr]) < abs(v[rightptr]))
{
ansV.push_back(v[rightptr] * v[rightptr]);
rightptr--;
}
else
{
ansV.push_back(v[leftptr] * v[leftptr]);
leftptr++;
}
}
reverse(ansV.begin(), ansV.end());
for (int ele : ansV)
{
cout << ele << " ";
}
cout << endl;
return;
}
int main()
{
int n;
cout << "Enter size of array: ";
cin >> n;
vector<int> v;
for (int i = 0; i < n; i++)
{
int ele;
cin >> ele;
v.push_back(ele);
}
sortedSquaredArray(v);
return 0;
}