【Likou】349. The intersection of two arrays<hash>

【Li Button】349. Intersection of Two Arrays

Given two arrays nums1 and nums2, return their intersection. Each element in the output must be unique. We can ignore the order of the output results.

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]
Explanation: [4,9] is also passable

提示:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000

answer

import java.util.HashSet;
import java.util.Set;

class Solution {
    
    
    public int[] intersection(int[] nums1, int[] nums2) {
    
    
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
    
    
            return new int[0];
        }
        
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> resSet = new HashSet<>();
        //遍历数组1
        for (int i : nums1) {
    
    
            set1.add(i);
        }
        //遍历数组2的过程中判断哈希表中是否存在该元素
        for (int i : nums2) {
    
    
            if (set1.contains(i)) {
    
    
                resSet.add(i);
            }
        }
      
        //方法1:将结果集合转为数组
        return resSet.stream().mapToInt(x -> x).toArray();
        
        //方法2:另外申请一个数组存放setRes中的元素,最后返回数组
        int[] arr = new int[resSet.size()];
        int j = 0;
        for(int i : resSet){
    
    
            arr[j++] = i;
        }
        
        return arr;
    }
}

Guess you like

Origin blog.csdn.net/qq_44033208/article/details/132495049