From 86b003d1469d098bc4efff8112260f4a82ac2a30 Mon Sep 17 00:00:00 2001 From: harshitagarwal260 <64749417+harshitagarwal260@users.noreply.github.com> Date: Sun, 10 Oct 2021 23:58:10 +0530 Subject: [PATCH] Update 977.java --- solutions/977.java | 39 ++++++++++++++------------------------- 1 file changed, 14 insertions(+), 25 deletions(-) diff --git a/solutions/977.java b/solutions/977.java index 845ca48..f047bd5 100644 --- a/solutions/977.java +++ b/solutions/977.java @@ -1,29 +1,18 @@ import java.util.*; class Solution { - public int[] sortedSquares(int[] nums) { - int[] arr = new int[nums.length]; - int i = 0; - int j = nums.length - 1; - int b = nums.length - 1; - while (i <= j) { - if (i == j) { - arr[b--] = nums[i] * nums[i]; - break; - } - if (Math.abs(nums[i]) > Math.abs(nums[j])) { - arr[b--] = nums[i] * nums[i]; - i++; - } else if (Math.abs(nums[i]) < Math.abs(nums[j])) { - arr[b--] = nums[j] * nums[j]; - j--; - } else if (Math.abs(nums[i]) == Math.abs(nums[j])) { - arr[b--] = nums[i] * nums[i]; - arr[b--] = nums[i] * nums[i]; - i++; - j--; - } + public int[] sortedSquares(int[] A) { + int n = A.length; + int[] result = new int[n]; + int i = 0, j = n - 1; + for (int p = n - 1; p >= 0; p--) { + if (Math.abs(A[i]) > Math.abs(A[j])) { + result[p] = A[i] * A[i]; + i++; + } else { + result[p] = A[j] * A[j]; + j--; + } + } + return result; } - return arr; - } -}