C# solution: dictionary


  • 0
    B
    public class Solution 
    {
        public int[] Intersect(int[] nums1, int[] nums2) 
    	{
            var numAndCount1 = new Dictionary<int, int>();
    
    		foreach(var num in nums1)
    		{
    			if (!numAndCount1.ContainsKey(num))		numAndCount1[num] = 0;
    
    			numAndCount1[num]++;
    		}
    
    		var result = new List<int>();
    
    		foreach(var num in nums2)
    		{
    			if (numAndCount1.ContainsKey(num) && numAndCount1[num] > 0)
    			{
    				result.Add(num);
    
    				numAndCount1[num]--;
    			}
    		}
    
    		return result.ToArray();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.