LeetCode oj 349. Intersection of Two Arrays(HashSet)
阿新 • • 發佈:2019-01-08
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.
HashSet:public class Solution { public int[] intersection(int[] nums1, int[] nums2) { int len1 = nums1.length; int len2 = nums2.length; int hash1[] = new int [65535]; int hash2[] = new int [65535]; for(int i=0;i<len1;i++){ hash1[nums1[i]]++; } for(int i=0;i<len2;i++){ hash2[nums2[i]]++; } int index = 0; int count = 0; for(int i=0;i<len1;i++){ if(hash2[nums1[i]] == 0){ hash1[nums1[i]] = 0; } } for(int i=0;i<65535;i++){ if(hash1[i] != 0){ count++; } } int re[] = new int [count]; for(int i=0;i<65535;i++){ if(hash1[i] != 0){ re[index++] = i; } } return re; } }
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { HashSet<Integer>set = new HashSet<Integer>(); int len1 = nums1.length; int len2 = nums2.length; for(int i=0;i<len1;i++){ set.add(nums1[i]); } List<Integer>list = new ArrayList<Integer>(); for(int i=0;i<len2;i++){ if(set.contains(nums2[i])){ list.add(nums2[i]); set.remove(nums2[i]); } } int size = list.size(); int re[] = new int [size]; for(int i=0;i<size;i++){ re[i] = list.get(i); } return re; } }