原题网址:https://leetcode.com/problems/intersection-of-two-arrays/
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.
方法:通过集合求交集。
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for(int num: nums1) set1.add(num);
for(int num: nums2) if (set1.contains(num)) set2.add(num);
int[] result = new int[set2.size()];
int i=0;
for(int num: set2) result[i++] = num;
return result;
}
}