Advertisement
1988coder

977. Squares of a Sorted Array

Jan 28th, 2019
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.96 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/squares-of-a-sorted-array/
  2.  
  3. /**
  4.  * Two Pointer
  5.  *
  6.  * Refer:
  7.  * https://leetcode.com/problems/squares-of-a-sorted-array/discuss/221922/Java-two-pointers-O(N)
  8.  *
  9.  * Time Complexity: O(N)
  10.  *
  11.  * Space Complexity: O(1) (Excluding the result)
  12.  *
  13.  * N = Length of the input array.
  14.  */
  15. class Solution {
  16.     public int[] sortedSquares(int[] A) {
  17.         if (A == null || A.length == 0) {
  18.             return new int[0];
  19.         }
  20.  
  21.         int len = A.length;
  22.         int left = 0;
  23.         int right = len - 1;
  24.         int[] result = new int[len];
  25.         int i = len - 1;
  26.  
  27.         while (left <= right) {
  28.             if (Math.abs(A[right]) >= Math.abs(A[left])) {
  29.                 result[i] = A[right] * A[right];
  30.                 right--;
  31.             } else {
  32.                 result[i] = A[left] * A[left];
  33.                 left++;
  34.             }
  35.             i--;
  36.         }
  37.  
  38.         return result;
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement