-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntersectionOfTwoArrays.java
More file actions
129 lines (122 loc) · 3.22 KB
/
IntersectionOfTwoArrays.java
File metadata and controls
129 lines (122 loc) · 3.22 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package basic.doublePointer;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* https://leetcode.com/problems/intersection-of-two-arrays/
* 找出两个数组的交集
* 349. Intersection of Two Arrays
* Given two arrays, write a function to compute their intersection.
*
* Example 1:
*
* Input: nums1 = [1,2,2,1], nums2 = [2,2]
* Output: [2]
* Example 2:
*
* Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
* Output: [9,4]
* Note:
*
* Each element in the result must be unique.
* The result can be in any order.
*/
public class IntersectionOfTwoArrays {
/**时间复杂度O(N)
* 使用hashset的解法
* @param nums1
* @param nums2
* @return
*/
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> nums1Set = new HashSet<>();
Set<Integer> intersectionSet = new HashSet<>();
for (int n : nums1) {
nums1Set.add(n);
}
for (int n : nums2) {
if(nums1Set.contains(n)) {
intersectionSet.add(n);
}
}
int[] ans = new int[intersectionSet.size()];
int i = 0;
for (Integer n: intersectionSet) {
ans[i++] = n;
}
return ans;
}
/**
* 时间复杂度O(N*logN)
* 双指针解法
* @param nums1
* @param nums2
* @return
*/
public int[] intersection2(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
Set<Integer> intersectionSet = new HashSet<>();
int i=0,j=0;
while (i<nums1.length && j<nums2.length) {
if(nums1[i] < nums2[j]) {
i++;
}else if(nums1[i] > nums2[j]) {
j++;
}else {
intersectionSet.add(nums1[i]);
i++;
j++;
}
}
int[] ans = new int[intersectionSet.size()];
int k = 0;
for (Integer n: intersectionSet) {
ans[k++] = n;
}
return ans;
}
/**
* 二分搜索解法
* 时间复杂度O(N*logN)
* @param nums1
* @param nums2
* @return
*/
public int[] intersection3(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Set<Integer> set=new HashSet<>();
for (int num: nums2) {
if(binarySearch(nums1,num)) {
set.add(num);
}
}
int[] ans = new int[set.size()];
int i=0;
for (int n: set) {
ans[i++]=n;
}
return ans;
}
/**
* 查找target是否在nums中出现过,出现过返回true,未出现过返回false
* @param nums
* @param target
* @return
*/
public boolean binarySearch(int[] nums, int target) {
int lo=0;
int ho=nums.length;
while (lo < ho) {
int mid = lo + (ho-lo)/2;
if(nums[mid] == target) {
return true;
}else if(nums[mid]<target) {
lo=mid+1;
}else {
ho=mid;
}
}
return false;
}
}