1. 程式人生 > 實用技巧 >LeetCode0350.兩個陣列的交集 II

LeetCode0350.兩個陣列的交集 II

題目要求

演算法分析

將短陣列元素以及出現的次數存到字典中(元素->鍵,出現次數->值),

遍歷長陣列的元素,如果該元素在字典中的個數大於0,則將字典中以該元素為鍵的值減1.並把元素存到結果陣列中.

程式碼展示(C#)

public class Solution
{
    Dictionary<int, int> dic = new Dictionary<int, int>();

    public int[] Intersect(int[] nums1, int[] nums2)
    {
        int[] res = null;

        
if(nums1.Length > nums2.Length) { res = MyFunc(nums2, nums1); } else { res = MyFunc(nums1, nums2); } return res; } public int[] MyFunc(int[] nums1, int[] nums2) { List<int> res = new List<int>();
foreach (var item in nums1) { if (dic.ContainsKey(item)) { dic[item]++; } else { dic.Add(item, 1); } } foreach (var item in nums2) { if (dic.ContainsKey(item)) {
if (dic[item] > 0) { res.Add(item); dic[item]--; } } } return res.ToArray(); } }

提交結果