Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. class Solution {
  2. public int[] sortedSquares(int[] A) {
  3.  
  4. int n = A.length;
  5. int[] squares = new int[n];
  6. int index = 0;
  7.  
  8. // found first positive >= 0
  9. int pos = 0;
  10. while (pos < n && A[pos] < 0) {
  11. pos++;
  12. }
  13.  
  14. int left = pos - 1;
  15. int right = pos;
  16.  
  17. while (left >= 0 || right < n) {
  18. if (left < 0) {
  19. int absRight = Math.abs(A[right]);
  20. squares[index] = absRight * absRight;
  21. right++;
  22. index++;
  23. continue;
  24. }
  25.  
  26. if (right >=n) {
  27. int absLeft = Math.abs(A[left]);
  28. squares[index] = absLeft * absLeft;
  29. left--;
  30. index++;
  31. }
  32.  
  33. int absLeft = Math.abs(A[left]);
  34. int absRight = Math.abs(A[right]);
  35. if (absLeft < absRight) {
  36. squares[index] = absLeft * absLeft;
  37. left--;
  38. index++;
  39. } else {
  40. squares[index] = absRight * absRight;
  41. right++;
  42. index++;
  43. }
  44. }
  45.  
  46. return squares;
  47.  
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement