Leetcode349. 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.

题目要求:

题目要求我们返回两个数组的交集,需要注意的是结果集的元素必须是有序并且唯一的。

解题思路:
- 可以使用首先将一个数组存入HashSet中,然后将第二个数组中的元素分别依次比较,看是否在HashSet中,如果存在则添加到需要返回的结果数组中。

最终实现:

public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            if (nums1 == null || nums2 == null) {
                return null;
            }
            Set<Integer> set1 = new HashSet<>();
            for (int i:nums1) {
                set1.add(i);
            }

            Set<Integer> set2 = new HashSet<>();
            for (int i:nums2) {
                if (set1.contains(i)) {
                    set2.add(i);
                }
            }

            int[] result = new int[set2.size()];
            int i = 0;
            for (int n:set2) {
                result[i++] = n;
            }
            return result;
        }
    }

这种方法时间复杂度为O(n),空间复杂度为O(n)。

另外的解:

  • 另外一种解题思路是,首先对数组进行排列,然后借助Arrays中的binarySearch方法,对每个元素进行二分查找,具体实现如下:
public class Solution {
        public static int[] intersection(int[] num1, int[] num2) {
            Arrays.sort(num1);
            Arrays.sort(num2);

            ArrayList<Integer> aList = new ArrayList<>();
            for (int i = 0; i < num1.length; i++) {
                if (i == 0 || (i > 0 && num1[i] != num1[i-1])) {
                    if (Arrays.binarySearch(num2, num1[i]) > -1) {
                        aList.add(num1[i]);
                    }
                }
            }
            int[] result = new int[aList.size()];
            int k = 0;
            for (int i : aList) {
                result[k++] = i;
            }
            return result;
        }
    }

对于上面的binarySearch方法,即可以自己实现也可以调用Arrays类中的静态方法,在这里就不实现了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值