I wonder if it could be solved with O(N) time complexity and no additional array declared.
class Solution {
public int[] sortedSquares(int[] A) {
int flag = 0;
if(A.length==1){
A[0]=A[0]*A[0];
return A;
}
if(A[0] >=0){
flag=1;
}
if(A[A.length-1]<=0){
flag=2;
}
int pivot=A.length;
for(int i=0; i<A.length; i++){
if(A[i]>=0 && pivot==A.length){
pivot=i;
}
A[i]=A[i]*A[i];
}
if(flag==1){
return A;
}
if(flag==2){
for(int i=0; i<A.length/2; i++){
int temp=A[i];
A[i]=A[A.length-i-1];
A[A.length-i-1]=temp;
}
return A;
}
for(int i=0; i < pivot/2; i++){
int temp=A[i];
A[i]=A[pivot-i-1];
A[pivot-i-1]=temp;
}
int left=0;
int right=pivot;
for(int i=0; i<A.length; i++){
if(left>=pivot){
break;
}
if(right>=A.length){
int leftComp=0;
if(i>=pivot){
leftComp=i;
}else{
leftComp=pivot;
}
int temp=A[i];
A[i]=A[leftComp];
A[leftComp]=temp;
left++;
continue;
}
if(right-pivot >0){
int leftComp=0;
if(i>pivot){
leftComp=i;
}else{
leftComp=pivot;
}
if(A[leftComp]<=A[right]){
int temp=A[i];
A[i]=A[leftComp];
A[leftComp]=temp;
left++;
}else{
int temp=A[i];
A[i]=A[right];
A[right]=temp;
right++;
}
}else{
if(A[left]<=A[right]){
left++;
}else{
int temp=A[i];
A[i]=A[right];
A[right]=temp;
right++;
}
}
}
return A;
}
}I've been working on like this but it also occurs error.
If somebody solved this, and share your code, I will be very appreciate.