Intersection of Two Arrays II

Intersection of Two Arrays II

Description

Given two arrays, write a function to compute their intersection.

Note
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.

Example 1:

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

Tags: Array、Sort

解读题意

给出两个数组,找出它们的交集。结果允许重复;结果无序排序

思路1

  1. 先对两个数组进行排序
  2. 定义两个指针i和j,分别来控制nums1和nums2。比较nums[i]nums[j],若nums[i] > nums[j]j+1,若nums[i] < nums[j]i+1,否则将nums[i]添加到结果集中,并且i和j均+1
class Solution {

   public int[] intersect(int[] nums1, int[] nums2) {

        if (nums1 == null || nums2 == null ||
                nums1.length == 0 || nums2.length == 0)
            return new int[]{};

        Arrays.sort(nums1);
        Arrays.sort(nums2);

        int i = 0, j = 0;
        List<Integer> list = new ArrayList<>();
        while (i < nums1.length && j < nums2.length) {

            if (nums1[i] < nums2[j])
                i++;
            else if (nums1[i] > nums2[j])
                j++;
            else {
                list.add(nums1[i]);
                i++;
                j++;
            }
        }

        int[] result = new int[list.size()];
        int index = 0;
        for (int x : list) {
            result[index++] = x;
        }

        return result;
   }
}

time complexity:O(n)

leetCode汇总:https://blog.csdn.net/qingtian_1993/article/details/80588941

项目源码,欢迎star:https://github.com/mcrwayfun/java-leet-code

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值