C#LeetCode刷题之#350-两个数组的交集 II(Intersection of Two Arrays II)

C#LeetCode刷题之#350-两个数组的交集 II(Intersection of Two Arrays II)

问题

给定两个数组,编写一个函数来计算它们的交集。

输入: nums1 = [1,2,2,1], nums2 = [2,2]

输出: [2,2]

输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]

输出: [4,9]

说明:

输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
我们可以不考虑输出结果的顺序。

进阶:

如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小很多,哪种方法更优?
如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?

Given two arrays, write a function to compute their intersection.

Input: nums1 = [1,2,2,1], nums2 = [2,2]

Output: [2,2]

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]

Output: [4,9]

Note:

Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.

Follow up:

What if the given array is already sorted? How would you optimize your algorithm?
What if nums1’s size is small compared to nums2’s size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

示例

public class Program {

    public static void Main(string[] args) {
        var nums1 = new int[] { 4, 9, 4, 5 };
        var nums2 = new int[] { 9, 4, 9, 8, 4 };

        var res = Intersection(nums1, nums2);
        ShowArray(res);

        Console.ReadKey();
    }

    private static void ShowArray(int[] array) {
        foreach(var num in array) {
            Console.Write($"{num} ");
        }
        Console.WriteLine();
    }

    private static int[] Intersection(int[] nums1, int[] nums2) {
        var list = new List<int>();
        var dic = new Dictionary<int, int>();

        for(var i = 0; i < nums1.Length; i++) {
            if(dic.ContainsKey(nums1[i])) {
                dic[nums1[i]]++;
            } else {
                dic[nums1[i]] = 1;
            }
        }

        for(var i = 0; i < nums2.Length; i++) {
            if(dic.ContainsKey(nums2[i]) && dic[nums2[i]] != 0) {
                list.Add(nums2[i]);
                dic[nums2[i]]--;
            }
        }

        return list.ToArray();
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

9 4 4

分析:

显而易见,以上算法的时间复杂度为: O(n)​ 。

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/4044

发表评论

登录后才能评论