-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSquaring_A_Sorted_Array.cpp
More file actions
60 lines (47 loc) · 1.25 KB
/
Squaring_A_Sorted_Array.cpp
File metadata and controls
60 lines (47 loc) · 1.25 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
52
53
54
55
56
57
58
59
60
/*Problem Statement:
Given a sorted array, create a new array containing squares of all the number of the input array in the sorted order.
*/
/*Example:
Input: [-2, -1, 0, 2, 3]
Output: [0, 1, 4, 4, 9]
*/
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class Squaring_A_Sorted_Array
{
public:
static vector<int> Find_Sqaured_Sorted_Array(const vector<int>&arr)
{
int n=arr.size();
vector<int> squares(n);
int left=0;
int right=n-1;
int highestsquareindex=n-1;
while(left<=right)
{
int leftsquare=arr[left]*arr[left];
int rightsquare=arr[right]*arr[right];
if(leftsquare<rightsquare)
{
squares[highestsquareindex--]=rightsquare;
right--;
}
else
{
squares[highestsquareindex--]=leftsquare;
left++;
}
}
return squares;
}
};
int main()
{
vector<int> result=Squaring_A_Sorted_Array::Find_Sqaured_Sorted_Array(vector<int>{-2,-1,0,2,3});
for(int i=0;i<result.size();i++)
{
cout<<result[i]<<" ";
}
cout<<endl;
}