6. 两个数组的交集

时间:2021-06-12
本文章向大家介绍6. 两个数组的交集,主要包括6. 两个数组的交集使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

两个数组的交集

[原题链接](初级算法 - LeetBook - 力扣(LeetCode)全球极客挚爱的技术成长平台 (leetcode-cn.com))

/**
 * 给定两个数组,编写一个函数来计算它们的交集。
 * 说明:
 * 输出结果中每个元素出现的次数,应与元素在两个数组中出现次数的最小值一致。
 * 我们可以不考虑输出结果的顺序。
 *
 * 进阶:
 * 如果给定的数组已经排好序呢?你将如何优化你的算法?
 * 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
 * 如果 nums2 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
 *
 */

public class Solution {
    /**
     * 思路:用big匹配small,设置标记数组mark[small.length]每次匹配元素成功后,
     * 对应small位置的标记值置true,count++,break;
     * 每次匹配前,判断当前small位置的对应mark是否为true,若为true,continue进行下一个位置的匹配;
     * 设置结果数组result[count],当mark[j]为true时,result[i] = small[j];
     * 时间复杂度O(m*n), 空间复杂度O(m)
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] intersect(int[] nums1, int[] nums2) {
        //令big为大数组,small为小数组
        int[] big, small;
        big = nums1.length > nums2.length ? nums1 : nums2;
        small = big == nums1 ? nums2 : nums1;
        int count = 0;
        boolean[] mark = new boolean[small.length];
        //用big匹配small
        for (int i = 0; i < big.length; i++) {
            for (int j = 0; j < small.length; j++) {
                if (mark[j]) continue;
                //匹配成功
                if (small[j] == big[i]){
                    mark[j] = true;
                    count++;
                    break;
                }
            }
        }
        int[] result = new int[count];
        for (int i = 0, j = 0; i < mark.length; i++){
            if (mark[i]) {
                result[j] = small[i];
                j++;
            }
        }
        return result;
    }
}

原文地址:https://www.cnblogs.com/getheading/p/14878636.html