C# - hash shorter of the 2 arrays


  • 0

    Same basic solution with potential optimization of checking which array is shorter to decide which to build hash from (use less space if possible)

        public int[] Intersect(int[] nums1, int[] nums2) 
        {
            int[] shorter = nums1.Length < nums2.Length ? nums1 : nums2;
            int[] longer = nums1.Length < nums2.Length ? nums2 : nums1;
            
            // extra space for the shorter of the 2 arrays
            Dictionary<int,int> map = new Dictionary<int,int>();
            foreach (int x in shorter)
            {
                if (map.ContainsKey(x)) map[x]++;
                else map[x] = 1;
            }
            
            IList<int> inter = new List<int>();
            foreach (int x in longer)
            {
                if (map.ContainsKey(x) && map[x]-- > 0) inter.Add(x);
            }
            
            return inter.ToArray();
        }
    

Log in to reply
 

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