1. 程式人生 > 其它 >Leetcode 350:Intersection of Two Arrays II

Leetcode 350:Intersection of Two Arrays II

技術標籤:資料結構javaleetcode演算法雜湊

Leetcode 350:Intersection of Two Arrays II

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

說人話:

求兩個陣列的交集。

舉例1:

image-20210126100314908

舉例2:

image-20210126100330274

[法1] Map 記錄頻次

思路

因為是求交集,所以元素出現的次數是需要進行考慮了。這裡筆者考慮到用 Map 這個集合框架來解決這個問題,主要是基於 key-value 的特性。使用 Map 可以記錄每個元素出現的頻次,然後得出交集。

思路如下:

  • 用一個 Map 存下 nums1 陣列,並記錄下每次元素出現的頻次
  • 判斷 nums2 的元素在 Map 中的出現頻次
    • 若 > 0,則說明有,將其放到一個臨時陣列中,並消耗一個頻次;
    • 若 = 0,則說明該元素不在 nums1 中,跳過。
  • 複製陣列,得到結果
程式碼
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {

        //記錄 nums1 中的元素及其頻次
        Map<Integer,Integer> numCount = new HashMap<>();

        for (int i = 0; i < nums1.
length; i++) { Integer integer = numCount.get(nums1[i]); if (integer == null){ numCount.put(nums1[i],1); }else{ Integer count = numCount.get(nums1[i]); numCount.put(nums1[i],++count); } } //臨時陣列,長度為 nums1 和 nums2 中短的那個
int[] result = new int[nums1.length<nums2.length?nums1.length:nums2.length]; //記錄交集中的元素個數 int count = 0; //判斷 nums2 中每個元素在 nums1 是否存在 for (int num: nums2){ Integer i = numCount.get(num); if (i != null && i > 0) { //存在的話放到臨時陣列中 result[count++]=num; //然後消耗一個頻次 numCount.put(num,--i); } } //複製陣列 int[] r = new int[count]; for (int i = 0; i < r.length; i++) { r[i] = result[i]; } return r; } }
提交結果
image-20210126133033579
程式碼分析

不考慮集合框架底層原理的話:

  • 時間複雜度:O(n)
  • 空間複雜度:O(n)