力扣LeetCode,兩個數組的交集 II

1、給定兩個數組,編寫一個函數來計算它們的交集。

示例 1:

1 輸入: nums1 = [1,2,2,1], nums2 = [2,2]
2 輸出: [2,2]

示例 2:

1 輸入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
2 輸出: [4,9]

說明:

  • 輸出結果中每個元素出現的次數,應與元素在兩個數組中出現的次數一致。
  • 我們可以不考慮輸出結果的順序。

進階:

  • 如果給定的數組已經排好序呢?你將如何優化你的算法?
  • 如果 nums1 的大小比 nums2 小很多,哪種方法更優?
  • 如果 nums2 的元素存儲在磁盤上,磁盤內存是有限的,並且你不能一次加載所有的元素到內存中,你該怎麼辦?

2、代碼實現,如下所示:

 1 package com.leetcode;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 import java.util.Map;
 6 import java.util.TreeMap;
 7 
 8 /**
 9  * @ProjectName: dataConstruct
10  * @Package: com.leetcode
11  * @ClassName: ArrayIntersection2
12  * @Author: biehl
13  * @Description: ${description}
14  * @Date: 2020/3/15 11:46
15  * @Version: 1.0
16  */
17 public class ArrayIntersection2 {
18 
19     public int[] intersect(int[] nums1, int[] nums2) {
20         Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
21         // 遍歷數組nums1
22         for (int num : nums1) {
23             // 如果Map集合中不包含此元素
24             if (!map.containsKey(num)) {
25                 // 就將num設置到map中,並將value值設置爲1
26                 map.put(num, 1);
27             } else {
28                 // 此時,如果map中包含了這個元素
29                 // 否則,將num的value值加一。
30                 map.put(num, map.get(num) + 1);
31             }
32         }
33 
34         List<Integer> list = new ArrayList<Integer>();
35         // 遍歷數組nums2
36         for (int num : nums2) {
37             // 判斷,如果map集合中包含了num這個key
38             if (map.containsKey(num)) {
39                 // 就將這個num添加到集合中
40                 list.add(num);
41                 // 此時將map集合中的num數字的頻數減一
42                 map.put(num, map.get(num) - 1);
43                 // 如果此時num的頻數是0,就刪除掉這個num
44                 if (map.get(num) == 0) {
45                     map.remove(num);
46                 }
47             }
48         }
49 
50         // 將List集合轉換爲int數組返回
51         int[] res = new int[list.size()];
52         for (int i = 0; i < list.size(); i++) {
53             res[i] = list.get(i);
54         }
55         return res;
56     }
57 
58     public static void main(String[] args) {
59 //        int[] nums1 = new int[]{1, 2, 2, 1};
60 //        int[] nums2 = {2, 2};
61 //        int[] nums1 = new int[]{4, 9, 5};
62 //        int[] nums2 = {9, 4, 9, 8, 4};
63 
64         int[] nums1 = new int[]{1, 1, 1, 1, 1, 1};
65         int[] nums2 = {1, 1, 1};
66         ArrayIntersection2 arrayIntersection = new ArrayIntersection2();
67         int[] intersection = arrayIntersection.intersect(nums1, nums2);
68         for (int i = 0; i < intersection.length; i++) {
69             System.out.println(intersection[i]);
70         }
71     }
72 
73 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章