Intersection of Two Arrays(多种方法)

本文介绍求解两数组交集的三种方法:哈希表、排序双指针及二分查找,对比不同场景下的时间与空间复杂度。

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

http://www.lintcode.com/en/problem/intersection-of-two-arrays/

题目:求两数组的交集(两数组长度分别为m,n),不包含重复元素


方法一:Hash

时间复杂度 O(n + m)   空间复杂度 O(min(m, n))


解答:将第一个数组的元素存入HashSet, 遍历第二个数组若有元素存在于HashSet中,将此元素存入temp set中。最后将tempSet中的元素转化为题目所需返回数组的形式;


第一次犯错:给结果数组分配了min(m, n)的空间,没有用到的位置会被自动填充0元素导致结果错误。应先用HashSet动态存储结果,最后进行转化即可;


代码:

public class Solution {
    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        // Write your code here
        if (nums1 == null || nums2 == null) {
            return null;
        }  
        
        int len1 = nums1.length;
        int len2 = nums2.length;
        Set<Integer> set = new HashSet<Integer>();
        Set<Integer> temp = new HashSet<Integer>();
    
        
        for (int i = 0; i < len1; i++) {
            set.add(nums1[i]);
        }
        for (int j = 0; j < len2; j++) {
            if (!set.contains(nums2[j])) {
                temp.add(nums2[j]);
            } 
        }
        
        int[] res = new int[temp.size()];
        int index = 0;
        for (Integer i : temp) {
            res[index] = i;
            index++;
        }
        return res;
    }
}


方法二:Merge two sorted arrays

时间复杂度O(nlogn + mlogm)     空间复杂度O(1)


解答:将两个数组排序后,分别从两个数组中最小元素开始依次比较,相同的元素存入temp(注意不可重复),最后将temp转化为固定长度的结果数组(去除未赋值的0元素);


备注:也可以将num1排序后,遍历num2中所有元素,依次用二分法在num1中寻找,时间复杂度为O(nlogn + mlogn),空间复杂度不变


代码:

public class Solution {
    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        // Write your code here
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i = 0;
        int j = 0;
        int index = 0;
        int[] temp = new int[nums1.length];
        
        while (i < nums1.length && j < nums2.length) {
            if (nums1[i] == nums2[j] && (index == 0 || nums1[i] != temp[index - 1])) {
                temp[index++] = nums1[i];
            } else if (nums1[i] < nums2[j]) {
                i++;
            } else {
                j++;
            }
        }
        
        int[] res = new int[index];
        for (int k = 0; k < index; k++) {
            res[k] = temp[k];
        }
        return res;
    }
}


方法三:Binary Search(二分法排序)

时间复杂度O(nlogn + mlogm)     空间复杂度O(1)     适用于 m >> n的情况

相当于在num1数组中依次寻找num2中的每个元素。方法与 Search in rotated sorted array类似。

### 哈夫曼编码实现 哈夫曼编码是一种基于字符频率的压缩技术,通过构建一棵二叉树来生成最优前缀码。以下是针对字符串 `'The following code computes the intersection of two arrays'` 的 Python 实现过程。 #### 字符频率统计 首先需要统计输入字符串中每个字符的出现次数。这可以通过遍历字符串并记录每种字符的数量完成[^2]。 ```python from collections import Counter def calculate_frequencies(text): frequencies = Counter(text) return dict(frequencies) text = 'The following code computes the intersection of two arrays' frequencies = calculate_frequencies(text) print("Character Frequencies:", frequencies) ``` #### 构建哈夫曼树 利用字符及其对应的频率数据,可以按照以下方式构建哈夫曼树: 1. 创建一个优先队列(最小堆),其中每个节点表示一种字符以及其频率。 2. 不断取出两个具有最低频率的节点,创建一个新的内部节点作为它们的父亲,并将其频率设置为两子节点频率之和。 3. 将新节点重新加入优先队列,直到只剩下一个根节点为止。 ```python import heapq class HuffmanNode: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def build_huffman_tree(freq_dict): priority_queue = [] for char, freq in freq_dict.items(): node = HuffmanNode(char, freq) heapq.heappush(priority_queue, node) while len(priority_queue) > 1: l
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值