Skip to content

Commit 655c956

Browse files
refactor 350
1 parent 318e158 commit 655c956

File tree

2 files changed

+53
-4
lines changed

2 files changed

+53
-4
lines changed

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

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
package com.fishercoder.solutions;
22

3-
import java.util.ArrayList;
4-
import java.util.HashMap;
5-
import java.util.List;
6-
import java.util.Map;
3+
import java.util.*;
4+
75
/**
86
* 350. Intersection of Two Arrays II
97
*
@@ -40,4 +38,26 @@ public int[] intersect(int[] nums1, int[] nums2) {
4038
return list.stream().mapToInt(i -> i).toArray();
4139
}
4240
}
41+
42+
public static class Solution2 {
43+
public int[] intersect(int[] nums1, int[] nums2) {
44+
Arrays.sort(nums1);
45+
Arrays.sort(nums2);
46+
int i = 0;
47+
int j = 0;
48+
List<Integer> list = new ArrayList<>();
49+
while (i < nums1.length && j < nums2.length) {
50+
if (nums1[i] == nums2[j]) {
51+
list.add(nums1[i]);
52+
i++;
53+
j++;
54+
} else if (nums1[i] < nums2[j]) {
55+
i++;
56+
} else {
57+
j++;
58+
}
59+
}
60+
return list.stream().mapToInt(k -> k).toArray();
61+
}
62+
}
4363
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._350;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.assertArrayEquals;
8+
9+
public class _350Test {
10+
private static _350.Solution1 solution1;
11+
private static _350.Solution2 solution2;
12+
13+
@BeforeClass
14+
public static void setup() {
15+
solution1 = new _350.Solution1();
16+
solution2 = new _350.Solution2();
17+
}
18+
19+
@Test
20+
public void test1() {
21+
assertArrayEquals(new int[]{2, 2}, solution1.intersect(new int[]{1, 2, 2, 1}, new int[]{2, 2}));
22+
}
23+
24+
@Test
25+
public void test2() {
26+
assertArrayEquals(new int[]{2, 2}, solution2.intersect(new int[]{1, 2, 2, 1}, new int[]{2, 2}));
27+
}
28+
29+
}

0 commit comments

Comments
 (0)