LeetCode筆記:350. 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.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

大意:

給出兩個數組,寫一個函數來計算他們的交叉點。
例子:
給出數組 nums1 = [1,2,2,1],nums2 = [2,2],返回[2,2]。
注意:
在結果中每個元素出現的次數應該與他們在兩個數組中出現的次數一樣。
結果可以是亂序的。
進階:
如果給出的數組已經是排好序的呢?你會如何優化你的算法?
如果nums1的尺寸比nums2要小呢?哪個算法更好?
如果nums2中的元素是存儲在硬盤上的,而由于內存是有限的你不能一次把所有元素都加載到內存中,怎么辦?

思路:

這個問題是之前一個問題的簡單變形:傳送門:LeetCode筆記:349. Intersection of Two Arrays。這個題目的變化在于他不要求每個數字只出現一次了,而是要求交叉了幾次就保留幾次,這其實更簡單,還是之前題目的解法,把保障數字唯一性的代碼去掉就好了,速度依然很快,3ms。
對于它提出來的三個問題,解答如下:

  • 如果數組已經排好序了,更簡單,把排序過程都省掉。
  • 如果nums1尺寸更小,這其實對于我的解法不影響,反正哪個數組先遍歷完都會結束循環。
  • 如果nums2的元素不能一次讀取,那就一個個讀取然后在nums1中尋找相同的數字,只是如果找到了記得要在nums1中去掉該位置的數字,等把nums2比較完了或者nums1被減沒了就結束了。

代碼(Java):

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int results[] = new int[nums1.length];// 結果數組
        
        // 沒有數字的情況
        if (nums1.length == 0 || nums2.length == 0) {
            return new int[0];
        }
        
        // 先對兩個數組排序
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        
        int index = 0;
        for (int i = 0, j = 0; i < nums1.length; ) {
            if (nums1[i] < nums2[j]) {// 第一個數組中數字小
                i++;
            } else if (nums1[i] == nums2[j]) {// 數字相同,放入結果數組
                results[index] = nums1[i];
                index++;
                i++;
                // 判斷第二個數組有沒有到最后一個數組,還沒到才繼續往后移去比
                if (j < nums2.length-1) j++;
                else break;
            } else {// 第二個數組中數字小,注意要判斷是否到達最后一個數字
                if (j < nums2.length-1) j++;
                else break;
            }
        }
        
        return Arrays.copyOfRange(results, 0, index);// 結果數組只返回有數字的那一部分
    }
}

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容