Simple O(n) solution in C++!


#1

vector Solution::solve(vector &A) {
vector v;
int n=A.size();
int k=n-1, i=0;
while(i<=k){
if(A[i]<0 && (-1)*A[i]>A[k]){
v.push_back(A[i]*A[i]);
i++;
} else {
v.push_back(A[k]*A[k]);
k–;
}
}
for(i=0; i<n/2; i++){ // reverse the vector v to get an ascendingly sorted array.
swap(v[i], v[n-i-1]);
}
return v;

}