349. 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.

链接:

https://leetcode.com/problems/intersection-of-two-arrays/?tab=Description

3/12/2017

需要熟悉Java各种数据结构的函数,比如HashSet可以直接一步到Integer Array,但是不可以到int[],除非手动遍历

 1 public class Solution {
 2     public int[] intersection(int[] nums1, int[] nums2) {
 3         HashSet<Integer> h1 = new HashSet<Integer>();
 4         HashSet<Integer> h2 = new HashSet<Integer>();
 5 
 6         for (int c: nums1) {
 7             h1.add(c);
 8         }
 9         for (int c: nums2) {
10             if (h1.contains(c)) h2.add(c);
11         }
12         int ret[] = new int[h2.size()];
13         int i = 0;
14         for (Integer e: h2) {
15             ret[i++] = e;
16         }
17         return ret;
18     }
19 }
原文地址:https://www.cnblogs.com/panini/p/6540615.html