349. Intersection of Two Arrays
Posted optor
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了349. Intersection of Two Arrays相关的知识,希望对你有一定的参考价值。
原题链接:https://leetcode.com/problems/intersection-of-two-arrays/description/
实现如下:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(Arrays.toString(s.intersection(new int[]{1, 2, 2, 1}, new int[]{2, 2})));
}
/**
* 看到这道题目我首先想到的是直接使用哈希表,然后看了下 Related Topics:Hash Table, Two Pointers, Binary Search, Sort。里面确实
* 提到了哈希表
*
* @param nums1
* @param nums2
* @return
*/
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null) {
return new int[0];
}
Set<Integer> set1 = new HashSet<>(nums1.length);
for (int i = 0; i < nums1.length; i++) {
set1.add(nums1[i]);
}
Set<Integer> set2 = new HashSet<>(nums2.length);
for (int i = 0; i < nums2.length; i++) {
if (set1.contains(nums2[i])) {
set2.add(nums2[i]);
}
}
int[] res = new int[set2.size()];
int i = 0;
for (int item : set2) {
res[i++] = item;
}
return res;
}
}
以上是关于349. Intersection of Two Arrays的主要内容,如果未能解决你的问题,请参考以下文章
349. Intersection of Two Arrays
349. Intersection of Two Arrays
Leetcode 349. Intersection of Two Arrays
[leetcode]349.Intersection of Two Arrays