Intersection of Two Arrays II

本文介绍了解决数组交集问题的两种不同方法:一种是非排序方式,使用哈希映射来记录元素及其出现次数;另一种是排序方式,通过先排序两个数组,然后用双指针技巧找到共同元素。这两种方法各有优缺点,适用于不同的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这道题的非排序做法值得自己再好好看看,尤其是while循环中的三个条件

非排序

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
		int [] result = new int[0];
		if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
			return result;
		}
        List<Integer/*value*/> list = new LinkedList<>();
		Map<Integer/*value*/,Integer/*number*/> map = new HashMap<>();
		for (int i: nums1) {
			if (map.containsKey(i)){
				map.put(i, map.get(i) + 1);
			} else {
				map.put(i, 1);
			}
		}
		for (int i: nums2) {
			if (map.containsKey(i) && map.get(i) > 0){
				list.add(i);
				map.put(i, map.get(i) - 1);
			}
		}
		result = new int[list.size()];
		int i = 0;
		for (int k: list) {
			result[i++] = k;
		}
		return result;
    }
}

排序的方法

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
		int [] temp = new int[0];
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return temp;
        }
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i = 0, j = 0, k = 0;
        temp = new int[nums1.length];
        while (i < nums1.length && j < nums2.length) {
            //if (nums1[i] != nums2[j]) {
            if (nums1[i] < nums2[j]) {
                i++;
            } else if (nums1[i] == nums2[j]) {
                temp[k++] = nums1[i];
                i++;
                j++;
            } else {
                j++;
            }
        }
        int[] result = new int[k];
        for (int m = 0; m < k; m++) {
            result[m] = temp[m];
        }
        return result;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值