File tree Expand file tree Collapse file tree 1 file changed +16
-12
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +16
-12
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
3
import java .util .ArrayList ;
4
- import java .util .Arrays ;
5
4
import java .util .List ;
6
- import java .util .Set ;
7
- import java .util .stream .Collectors ;
8
5
9
6
/**
10
7
* 1213. Intersection of Three Sorted Arrays
24
21
* */
25
22
public class _1213 {
26
23
public static class Solution1 {
24
+ /**credit: https://leetcode.com/problems/intersection-of-three-sorted-arrays/discuss/397603/Simple-Java-solution-beats-100*/
27
25
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 ++;
34
40
} else {
35
- if (set2 .contains (arr1 [i ]) && set3 .contains (arr1 [i ])) {
36
- result .add (arr1 [i ]);
37
- }
41
+ k ++;
38
42
}
39
43
}
40
44
return result ;
You can’t perform that action at this time.
0 commit comments