Leetcode之Intersection of Two Arrays 问题

问题描述:

Given two arrays, write a function to compute their intersection(交集).

Note:

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

示例:

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return[2].

问题来源:Intersection of Two Arrays (详细地址:https://leetcode.com/problems/intersection-of-two-arrays/description/)

思路分析:题目要求的是两个数组的交集,重复的数字只记录一次(所以肯定会使用set)。乍一想,题目的解法还是相当多的,在这我介绍几种比较常见的解法:

解法一:采用两个HashSet。具体的解法是:先将一个数组中的元素存放到一个set中,然后遍历另外的一个数组,判断刚才的set中是否含有该元素,如果有的话,那我们就添加到另外的一个集合intersection中,最后申请一个数组,将集合intersection中的元素都赋值到数组中去;

解法二:采用排序+一个hashset。我们换个角度思考一下,我们先将两个数组进行排序,接着我们指派两个指针,其中一个指针i指向一个已经排好序的数组nums1,另外一个指针j指向另外一个排好序的数组,我们比较当前这两指针指向的数字的大小,哪个数字更小,咱们就动哪个指针,即:

1.)nums1[i] < nums2[j]     i++;

2.)nums1[i] > nums2[j]     j++;

                                              3.)nums1[i] == nums2[j]    i++; j++;并将这个数保存到set中

解法三:利用二分查找试试:我们先将其中一个数组排好序,接着我们遍历第二个数组,每遍历一个数,我们就在这个排好序的数组中进行查找,也是就是说每遍历一个数,我们就要调用一次二分查找,最后也是得添加到一个hashset中;

解法四:在这采用很简单的代码,只有两行,我们采用jdk8里面的“流”的用法和函数式编程来解决。

代码:

解法一:

Leetcode之Intersection of Two Arrays 问题

解法二:

Leetcode之Intersection of Two Arrays 问题

解法三:

主体部分:

Leetcode之Intersection of Two Arrays 问题

二分查找:

Leetcode之Intersection of Two Arrays 问题

解法四:

Leetcode之Intersection of Two Arrays 问题