Skip to content

Commit 1efa219

Browse files
add a solution for 977
1 parent 91b52fd commit 1efa219

File tree

2 files changed

+46
-20
lines changed

2 files changed

+46
-20
lines changed

src/main/java/com/fishercoder/solutions/_977.java

+26-4
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,35 @@
44

55
public class _977 {
66
public static class Solution1 {
7-
public int[] sortedSquares(int[] A) {
8-
int[] result = new int[A.length];
9-
for (int i = 0; i < A.length; i++) {
10-
result[i] = (int) Math.pow(A[i], 2);
7+
/**
8+
* O(nlogn) solution
9+
*/
10+
public int[] sortedSquares(int[] nums) {
11+
int[] result = new int[nums.length];
12+
for (int i = 0; i < nums.length; i++) {
13+
result[i] = (int) Math.pow(nums[i], 2);
1114
}
1215
Arrays.sort(result);
1316
return result;
1417
}
1518
}
19+
20+
public static class Solution2 {
21+
/**
22+
* O(n) solution
23+
*/
24+
public int[] sortedSquares(int[] nums) {
25+
int[] ans = new int[nums.length];
26+
for (int i = nums.length - 1, left = 0, right = nums.length - 1; i < nums.length && left <= right; i--) {
27+
if (Math.abs(nums[left]) < Math.abs(nums[right])) {
28+
ans[i] = nums[right] * nums[right];
29+
right--;
30+
} else {
31+
ans[i] = nums[left] * nums[left];
32+
left++;
33+
}
34+
}
35+
return ans;
36+
}
37+
}
1638
}

src/test/java/com/fishercoder/_977Test.java

+20-16
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,27 @@
77
import static org.junit.Assert.assertArrayEquals;
88

99
public class _977Test {
10-
private static _977.Solution1 solution1;
11-
private static int[] A;
10+
private static _977.Solution1 solution1;
11+
private static _977.Solution2 solution2;
12+
private static int[] A;
1213

13-
@BeforeClass
14-
public static void setup() {
15-
solution1 = new _977.Solution1();
16-
}
14+
@BeforeClass
15+
public static void setup() {
16+
solution1 = new _977.Solution1();
17+
solution2 = new _977.Solution2();
18+
}
1719

18-
@Test
19-
public void test1() {
20-
A = new int[] {-4, -1, 0, 3, 10};
21-
assertArrayEquals(new int[] {0, 1, 9, 16, 100}, solution1.sortedSquares(A));
22-
}
20+
@Test
21+
public void test1() {
22+
A = new int[]{-4, -1, 0, 3, 10};
23+
assertArrayEquals(new int[]{0, 1, 9, 16, 100}, solution1.sortedSquares(A));
24+
assertArrayEquals(new int[]{0, 1, 9, 16, 100}, solution2.sortedSquares(A));
25+
}
2326

24-
@Test
25-
public void test2() {
26-
A = new int[] {-7, -3, 2, 3, 11};
27-
assertArrayEquals(new int[] {4, 9, 9, 49, 121}, solution1.sortedSquares(A));
28-
}
27+
@Test
28+
public void test2() {
29+
A = new int[]{-7, -3, 2, 3, 11};
30+
assertArrayEquals(new int[]{4, 9, 9, 49, 121}, solution1.sortedSquares(A));
31+
assertArrayEquals(new int[]{4, 9, 9, 49, 121}, solution2.sortedSquares(A));
32+
}
2933
}

0 commit comments

Comments
 (0)