[Leetcode] 349. 两个数组的交集 java hashmap

给定两个数组,编写一个函数来计算它们的交集。

示例 1:

输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]

示例 2:

输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]

说明:

  • 输出结果中的每个元素一定是唯一的。
  • 我们可以不考虑输出结果的顺序。
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        HashMap<Integer,Integer> map1= new HashMap<Integer,Integer>();//nums1的map
        HashMap<Integer,Integer> map2= new HashMap<Integer,Integer>();//共同元素的map
        for(int i:nums1){
            if(!map1.containsKey(i)){
                map1.put(i,i);
            }       
        }
        for(int j:nums2){
            if(map1.containsKey(j) && !map2.containsKey(j)){
                map2.put(j,j);
            }
        }
        int[] result=new int[map2.size()];
        int index=0;
        for(int k:map2.keySet()){
            result[index++]=map2.get(k);
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/niceHou666/article/details/82973417