-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIntersectionOfTwoArrays.java
More file actions
83 lines (79 loc) · 2.48 KB
/
IntersectionOfTwoArrays.java
File metadata and controls
83 lines (79 loc) · 2.48 KB
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
public class Solution {
//Hashmap solution. O(n) time and O(n) space
public int[] intersection0(int[] nums1, int[] nums2) {
Set<Integer> uniqueNums = new HashSet<>();
for (int num : nums1) {
uniqueNums.add(num);
}
List<Integer> resultList = new ArrayList<>();
for (int num : nums2) {
if (uniqueNums.contains(num)) {
resultList.add(num);
uniqueNums.remove(num);
}
}
int[] result = new int[resultList.size()];
for (int i = 0; i < result.length; ++i) {
result[i] = resultList.get(i);
}
return result;
}
//Two pointers solution when the input arrays are sorted.
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer> resultList = new ArrayList<>();
for (int i1 = 0, i2 = 0; i1 < nums1.length && i2 < nums2.length;) {
if (i2 > 0 && nums2[i2] == nums2[i2-1]) {
i2++;
continue;
}
if (nums1[i1] == nums2[i2]) {
resultList.add(nums2[i2]);
}
if (nums1[i1] >= nums2[i2]) {
i2++;
} else {
i1++;
}
}
int i = 0;
int[] result = new int[resultList.size()];
for (int num : resultList) {
result[i++] = num;
}
return result;
}
//Second try
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer> result = new ArrayList<>();
for (int i1 = 0, i2 = 0; i1 < nums1.length && i2 < nums2.length;) {
if (i1 < nums1.length - 1 && nums1[i1] == nums1[i1+1]) {
i1++;
continue;
}
if (i2 < nums2.length - 1 && nums2[i2] == nums2[i2+1]) {
i2++;
continue;
}
if (nums1[i1] < nums2[i2]) {
i1++;
} else if (nums1[i1] > nums2[i2]) {
i2++;
} else {
result.add(nums1[i1]);
i1++;
i2++;
}
}
int[] nums = new int[result.size()];
int i = 0;
for (int num : result) {
nums[i++] = num;
}
return nums;
}
//Third solution is using binary search for each element of nums2 in nums1.
}