349. Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

  • Each element in the result must be unique.
  • The result can be in any order.
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> set1 = new HashSet<Integer>();
        for (Integer n : nums1) set1.add(n);
        HashSet<Integer> set2 = new HashSet<Integer>();
        for (Integer n : nums2) set2.add(n);
        
        int[] res = new int[Math.min(set1.size(), set2.size())];
        int ind = 0;
        for(Integer i: set1) if(set2.contains(i)) res[ind++] = i;
        return Arrays.copyOf(res, ind);
    }
}

要是我的话估计还要用一个hashmap,其实并不用,巧用数组以及Arrays.copyOf(orig array, length).

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12258286.html