1. 程式人生 > >leetcode (Intersection of Two Arrays II)

leetcode (Intersection of Two Arrays II)

Title: Intersection of Two Arrays II    350

Difficulty:Easy

原題leetcode地址:   https://leetcode.com/problems/intersection-of-two-arrays-ii/

 

1.  見程式碼註釋

時間複雜度:O(n),三次一層for迴圈。

空間複雜度:O(n),申請map和連結串列list以及需要返回的陣列。

    /**
     * nums1資料存放map中
     * nums1和nums2中相同且重複的資料存放list中
     * 將list中資料轉換成返回的陣列
     * @param nums1
     * @param nums2
     * @return
     */
    public static int[] intersect(int[] nums1, int[] nums2) {

        if (nums1.length == 0 || nums2.length == 0) {
            return new int[]{};
        }

        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> list = new ArrayList<>();

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

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

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

        return res;

    }