0
点赞
收藏
分享

微信扫一扫

HashSet:提取两个数组的重复的值

给定两个数组 nums1nums2 ,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序

题目:力扣

基础:

集合基本函数和属性

class Solution {
    //利用set的不可重复性
    public int[] intersection(int[] nums1, int[] nums2) {
        
        if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length==0){
            return new int[0];
        }
        //set1 用于储存nums1中的值,不重复
        //resSet 用于存储两数组个相同的值
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> resSet = new HashSet<>();
        //遍历数组1
        for(int i : nums1){
            // set1.add(nums1[i]),这样写直接是错的,i直接代表是对应的元素值
            set1.add(i);
        }
        //遍历数组2,把相同的元素放入resSet
        for(int i : nums2){
            //set包含元素的方法contains
            if(set1.contains(i)){
                resSet.add(i);
            }
        }
        //将set中的值添加到数组中
        int[] resArr = new int[resSet.size()];
        int index = 0;
        for(int i : resSet){
            resArr[index++]=i;
        }
        return resArr;
    }
}
举报

相关推荐

0 条评论