349. Intersection of Two Arrays

本文提供了一种解决LeetCode中两数组交集问题的方法,通过使用哈希表来高效地找出两个整数数组的公共元素。代码示例清晰展示了算法实现过程。

原题链接:https://leetcode.com/problems/intersection-of-two-arrays/description/
实现如下:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(Arrays.toString(s.intersection(new int[]{1, 2, 2, 1}, new int[]{2, 2})));
    }

    /**
     * 看到这道题目我首先想到的是直接使用哈希表,然后看了下 Related Topics:Hash Table, Two Pointers, Binary Search, Sort。里面确实
     * 提到了哈希表
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null) {
            return new int[0];
        }
        Set<Integer> set1 = new HashSet<>(nums1.length);
        for (int i = 0; i < nums1.length; i++) {
            set1.add(nums1[i]);
        }
        Set<Integer> set2 = new HashSet<>(nums2.length);
        for (int i = 0; i < nums2.length; i++) {
            if (set1.contains(nums2[i])) {
                set2.add(nums2[i]);
            }
        }
        int[] res = new int[set2.size()];
        int i = 0;
        for (int item : set2) {
            res[i++] = item;
        }
        return res;
    }

}

转载于:https://www.cnblogs.com/optor/p/8758997.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值