349. Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

https://discuss.leetcode.com/topic/45685/three-java-solutions

** 解題思路**
三種解法:

  1. Use two hash sets , O(n) Time complexity
    先把nums1加入到set中,然后用nums2中元素在set中遍歷,如果set包含該元素,就加入到intersect set中。最后把intersect set 存入結果數組。

  2. Sort both arrays, use two pointers O(nlogn) Time complexity

  3. Binary search O(nlogn) Time complexity
    先sort nums2 ,然后用nums1元素在nums2中做binary search。如果能找到,就加入結果集。

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

推薦閱讀更多精彩內容