LeetCode Intersection of Two Arrays II

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

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.
题意:给出两个数组,求出其交集

代码如下:

class Solution
{
    public int[] intersect(int[] nums1, int[] nums2)
    {
        List list = new ArrayList();
        Map map = new HashMap();

        for (int i = 0; i < nums1.length; i++)
        {
            if (map.containsKey(nums1[i]))
            {
                map.put(nums1[i], map.get(nums1[i]) + 1);
            }
            else
            {
                map.put(nums1[i], 1);
            }
        }

        for (int i = 0; i < nums2.length; i++)
        {
            if (map.containsKey(nums2[i]))
            {
                list.add(nums2[i]);
                map.put(nums2[i], map.get(nums2[i]) - 1);

                if (0 == map.get(nums2[i]))
                {
                    map.remove(nums2[i]);
                }
            }
        }

        int[] ans = new int[list.size()];
        for (int i = 0; i < list.size(); i++)
        {
            ans[i] = list.get(i);
        }

        return ans;
    }
}



你可能感兴趣的:(#)