Skip to content

Instantly share code, notes, and snippets.

@yangpeng-chn
Created June 14, 2019 15:12
Show Gist options
  • Save yangpeng-chn/44aba667b96e2356841dd9a9fd2f8c80 to your computer and use it in GitHub Desktop.
Save yangpeng-chn/44aba667b96e2356841dd9a9fd2f8c80 to your computer and use it in GitHub Desktop.
Two Pointers or Iterators
vector<int> sortedSquares(vector<int>& A) {
vector<int> res(A.size());
int left = 0, right = 0;
/*for(int i = 0; i < A.size(); i++){
if(A[i] < 0){
}
if(A[i] >= 0){
right = i; //
left = right-1;
break;
}
}
if(A.back() <= 0){
left = A.size()-1;
right = left+1;
}*/
//improvement of above
while(right < A.size() && A[right] < 0){
right++;
}
left = right-1;
int j = 0;
while(left >= 0 && right < A.size()){
int a = A[left] * A[left];
int b = A[right] * A[right];
if(a < b){
res[j++] = a;
left--;
}else{
res[j++] = b;
right++;
}
}
while(left >= 0){
int a = A[left] * A[left];
res[j++] = a;
left--;
}
while(right < A.size()){
int b = A[right] * A[right];
res[j++] = b;
right++;
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment