-
Notifications
You must be signed in to change notification settings - Fork 0
349. Intersection of Two Arrays
Jacky Zhang edited this page Aug 9, 2016
·
1 revision
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
- Each element in the result must be unique.
- The result can be in any order.
Array类题目。
由于不能重复,因此可以采用HashSet来解。 将nums1的元素存入HashSet,若nums2中的元素在HashSet中,则属于两者的intersection。 最后转换为数组即可。
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> hs1 = new HashSet<Integer>();
for(int i : nums1) {
hs1.add(i);
}
Set<Integer> intersect = new HashSet<Integer>();
for(int i : nums2) {
if(hs1.contains(i)) {
intersect.add(i);
}
}
int[] res = new int[intersect.size()];
int i = 0;
for(Integer num : intersect) {
res[i++] = num;
}
return res;
}
}