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。如果能找到,就加入结果集。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容