Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [twenty two]return [2].
Note:
- Each element in the result must be unique.
- The result can be in any order.
I used two for loops for this problem, but I found that one loop is also sufficient. You can store the data first, and then add the second data. If you can't store the data, it's a duplicate.
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { HashSet set = new HashSet(); for(int i=0;i set) { int[] a = new int[set.size()]; int i = 0; for (Integer val : set) a[i++] = val; return a; } } This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:
Original author:Jake Tao,source:"LeetCode – 349. Intersection of Two Arrays"