The given array is sorted. We can use that to construct sorted squares array. Do the following
Code as follows (try to solve it yourself first)
class Solution {
public int[] sortedSquares(int[] A) {
int n = A.length;
int[] squares = new int[n];
int firstPos = 0;
for(int i=0;i<n;i++){
if(A[i] >= 0){
firstPos = i;
break;
}
}
int i = firstPos;
int j = firstPos-1;
if(i == -1){
j= n-1;
i = n;
}
int k = 0;
while(i < n || j >= 0){
int iVal = i < n ? Math.abs(A[i]) : Integer.MAX_VALUE;
int jVal = j >= 0 ? Math.abs(A[j]) : Integer.MAX_VALUE;
int min = 0;
if(iVal < jVal) {
min = iVal;
i++;
}else {
min = jVal;
j--;
}
squares[k++] = min*min;
}
return squares;
}
}