当前位置:网站首页>Leetcode- intersection of two arrays - simple

Leetcode- intersection of two arrays - simple

2022-06-13 05:47:00 AnWenRen

title :349 Intersection of two arrays - Simple

subject

Given two arrays , Write a function to calculate 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]

explain

  • Each element of the output must be unique .
  • We can ignore the order of output results .

Code Java

public int[] intersection(int[] nums1, int[] nums2) {
    
    Set result = new HashSet();
    Set set = new HashSet();
    for (int i = 0; i < nums1.length; i++) {
    
        set.add(nums1[i]);
    }
    for (int i = 0; i < nums2.length; i++) {
    
        if (set.contains(nums2[i])){
    
            result.add(nums2[i]);
        }
    }
    int[] re = new int[result.size()];
    int j = 0;
    for (Object o : result) {
    
        re[j++] = (int) o;
    }
    return re;
}
原网站

版权声明
本文为[AnWenRen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280507176495.html