Leetcode 350: Intersection of Two Arrays II

问题描述:
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
求两个数组的交集,不考虑顺序,不删减重复

限制条件:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000

思路:
先排序。每个集合设立一个头指针pt1,pt2,比较其指向的值,若pt1小于pt2,则pt1++;若相等,则加入该元素,且都++; 若pt1大于pt2,pt2++;
关键一点:如果遇到想使用array但是不确定其大小的情况,可以使用arraylist,最终转换为array。转换的方式有很多种,我这里用的是逐一get。因为使用toArray会出现数据类型不匹配的错误。

代码如下:

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        List<Integer> myList = new ArrayList<>();
        int pt1 = 0;
        int pt2 = 0;
        while ((pt1<nums1.length) && (pt2<nums2.length)){
            if(nums1[pt1]<nums2[pt2]){
                pt1++;
            }
            else if (nums1[pt1]==nums2[pt2]){
                myList.add(nums1[pt1]);
                pt1++;
                pt2++;
            }
            else{
                pt2++;
            }
        }
        int[] ans = new int[myList.size()];
        for (int i=0; i<myList.size(); i++){
            ans[i]=myList.get(i);
        }
        return ans;
    }
}

时间复杂度: O(nlogn), 受制于排序算法的速度。

方法二:用哈希表

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        //we assume nums1 is smaller than nums2 in length, otherwise we swap them first
        if(nums1.length>nums2.length){
            return intersect(nums2, nums1);
        }
        List<Integer> list=new ArrayList<>();
        Map<Integer, Integer> map=new HashMap<>();
        for(int i=0; i<nums1.length; i++){
            if(!map.containsKey(nums1[i])){
                map.put(nums1[i], 1);
            }
            else{
                map.replace(nums1[i], map.get(nums1[i])+1);
            }
        }
        for(int i=0; i<nums2.length; i++){
            if((map.containsKey(nums2[i]))&&(map.get(nums2[i])>0)){
                list.add(nums2[i]);
                map.replace(nums2[i], map.get(nums2[i])-1);
            }
        }
        int[] ans=new int[list.size()];
        for(int i=0; i<list.size(); i++){
            ans[i]=list.get(i);
        }
        return ans;
    }
}

时间复杂度: O(m+n)
空间复杂度: O(min(m,n))

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值