Skip to content

Commit b0b5203

Browse files
refactor 1213
1 parent aaedbe9 commit b0b5203

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

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

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

33
import java.util.ArrayList;
4-
import java.util.Arrays;
54
import java.util.List;
6-
import java.util.Set;
7-
import java.util.stream.Collectors;
85

96
/**
107
* 1213. Intersection of Three Sorted Arrays
@@ -24,17 +21,24 @@
2421
* */
2522
public class _1213 {
2623
public static class Solution1 {
24+
/**credit: https://leetcode.com/problems/intersection-of-three-sorted-arrays/discuss/397603/Simple-Java-solution-beats-100*/
2725
public List<Integer> arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
28-
List<Integer> result = new ArrayList<>();
29-
Set<Integer> set2 = Arrays.stream(arr2).boxed().collect(Collectors.toSet());
30-
Set<Integer> set3 = Arrays.stream(arr3).boxed().collect(Collectors.toSet());
31-
for (int i = 0; i < arr1.length; i++) {
32-
if (i >= arr2.length || i >= arr3.length) {
33-
break;
26+
List<Integer> result = new ArrayList();
27+
int i = 0;
28+
int j = 0;
29+
int k = 0;
30+
while (i < arr1.length && j < arr2.length && k < arr3.length) {
31+
if (arr1[i] == arr2[j] && arr1[i] == arr3[k]) {
32+
result.add(arr1[i]);
33+
i++;
34+
j++;
35+
k++;
36+
} else if (arr1[i] < arr2[j]) {
37+
i++;
38+
} else if (arr2[j] < arr3[k]) {
39+
j++;
3440
} else {
35-
if (set2.contains(arr1[i]) && set3.contains(arr1[i])) {
36-
result.add(arr1[i]);
37-
}
41+
k++;
3842
}
3943
}
4044
return result;

0 commit comments

Comments
 (0)