Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/squares-of-a-sorted-array/
- /**
- * Two Pointer
- *
- * Refer:
- * https://leetcode.com/problems/squares-of-a-sorted-array/discuss/221922/Java-two-pointers-O(N)
- *
- * Time Complexity: O(N)
- *
- * Space Complexity: O(1) (Excluding the result)
- *
- * N = Length of the input array.
- */
- class Solution {
- public int[] sortedSquares(int[] A) {
- if (A == null || A.length == 0) {
- return new int[0];
- }
- int len = A.length;
- int left = 0;
- int right = len - 1;
- int[] result = new int[len];
- int i = len - 1;
- while (left <= right) {
- if (Math.abs(A[right]) >= Math.abs(A[left])) {
- result[i] = A[right] * A[right];
- right--;
- } else {
- result[i] = A[left] * A[left];
- left++;
- }
- i--;
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement