forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_349.java
89 lines (83 loc) · 2.78 KB
/
_349.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.fishercoder.solutions;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class _349 {
public static class Solution1 {
//credit: https://leetcode.com/articles/intersection-of-two-arrays/
//Time: O(m+n) on average, O(m*n) in worse case
//Space: O(m+n)
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
Set<Integer> set2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
set1.retainAll(set2);
int[] intersection = new int[set1.size()];
int i = 0;
for (int num : set1) {
intersection[i++] = num;
}
return intersection;
}
}
public static class Solution2 {
//Time: O(nlgn)
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums2);
Set<Integer> intersect = new HashSet();
for (int i : nums1) {
if (binarySearch(i, nums2)) {
intersect.add(i);
}
}
int[] result = new int[intersect.size()];
int i = 0;
for (int num : intersect) {
result[i++] = num;
}
return result;
}
private boolean binarySearch(int i, int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == i) {
return true;
} else if (nums[mid] > i) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return false;
}
}
public static class Solution3 {
//use two pointers
//credit: https://leetcode.com/problems/intersection-of-two-arrays/discuss/81969/Three-Java-Solutions
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
Set<Integer> set = new HashSet<>();
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
set.add(nums1[i++]);
j++;
} else if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
int[] intersection = new int[set.size()];
int k = 0;
for (int num : set) {
intersection[k++] = num;
}
return intersection;
}
}
}