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?

** 解題思路**
這一題比較有意思。 Follow up三個問題,需要考慮兩個array的大小。第三問 參考這兩個分析:
第三問分析之一:

  • If only nums2 cannot fit in memory, put all elements of nums1 into a HashMap, read chunks of array that fit into the memory, and record the intersections.

  • If both nums1 and nums2 are so huge that neither fit into the memory, sort them individually (external sort), then read 2 elements from each array at a time in memory, record intersections.

第三問分析之二 補充:

Thanks for the solution. I think the second part of the solution is impractical, if you read 2 elements at a time, this procedure will take forever. In principle, we want minimize the number of disk access during the run-time.
An improvement can be sort them using external sort, read (let's say) 2G of each into memory and then using the 2 pointer technique, then read 2G more from the array that has been exhausted. Repeat this until no more data to read from disk.
But I am not sure this solution is good enough for an interview setting. Maybe the interviewer is expecting some solution using Map-Reduce paradigm.
** 參考代碼**


   /* Sort both arrays, use two pointers
      Arrays.sort(nums1); Arrays.sort(nums2);
      Test case: 
       [2,1]
       [1,1] -> [1]
   */
   public int[] intersect(int[] nums1, int[] nums2) {
       List<Integer> list = new ArrayList<>();
       Arrays.sort(nums1);
       Arrays.sort(nums2);
       int i = 0, j = 0;
       while(i < nums1.length &&  j < nums2.length) {
           if (nums1[i] > nums2[j]) {
               j++;
           } else if (nums1[i] < nums2[j]) {
               i++;
           } else {
             list.add(nums1[i]);
             i++;
             j++;
           }
       }
       int[] res = new int[list.size()];
       int k = 0;
       for (Integer e : list) {
           res[k++] = e;
       }
       return res;
   }
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容