Leetcode 350. Intersection of Two Arrays II

/**
 * This problem allows duplicate, then we cannot use hashset.
 * Solution is using hashmap, the key would be the number in the array, 
 * and the value is the number of times a key appeared. 
 * O(n)
 */ 
public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        HashMap<Integer, Integer> hm1 = new HashMap<Integer, Integer>();
        List<Integer> list = new ArrayList<>();
        
        // iterate the first array save the number and the times it appeared
        for (int num1 : nums1) {
            if (hm1.containsKey(num1)) 
                hm1.put(num1, hm1.get(num1)+1);     // increase count by 1
            else
                hm1.put(num1, 1);
        }
        
        // iterate the second array to find intersection, add number to the list if count is grater than 0
        for (int num2 : nums2) {
            if (hm1.containsKey(num2) && hm1.get(num2)>0) {
                list.add(num2);
                hm1.put(num2, hm1.get(num2)-1);     // decrease count by 1
            }
        }
        
        int[] ret = new int[list.size()];
        int k = 0;
        for (int l : list)
            ret[k++] = l;
        
        return ret;
    }
}
public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        List<Integer> list = new ArrayList<>();
        
        // sort tow arrays, O(nlogn)
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        
        // use two pointer to find intersection
        int i = 0, j = 0;
        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[] ret = new int[list.size()];
        int k = 0;
        for (int l : list)
            ret[k++] = l;
            
        return ret;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值