Java/350. Intersection of Two Arrays II 两个数组的交集 II

题目

Java/350. Intersection of Two Arrays II 两个数组的交集 II


Java/350. Intersection of Two Arrays II 两个数组的交集 II

 

 

 

代码部分一(4ms 85.80%)

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        List<Integer> list = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>();
        
        for(int i = 0; i < nums1.length; i++){
            map.put(nums1[i], map.getOrDefault(nums1[i], 0)+1);
        }
        for(int i = 0; i < nums2.length; i++){
            if(map.containsKey(nums2[i])){
                if(map.get(nums2[i]) > 0){
                    list.add(nums2[i]);
                    map.put(nums2[i], map.get(nums2[i]) - 1);
                }
            }
        }
    
        int[] res = new int[list.size()];
        for(int i = 0; i < res.length; i++){
            res[i] = list.get(i);
        }
        return res;
    }
}

 

代码部分二(4ms 85.80%)

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        int len3 = len1 > len2 ? len1 : len2;
        int[] res = new int[len3];
        
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        
        int i = 0;
        int j = 0;
        int k = 0;
        while(i < len1 && j < len2){
            if(nums1[i] == nums2[j]){
                res[k] = nums1[i];
                k++;
                i++;
                j++;
            }else 
                if(nums1[i] < nums2[j]){
                    i++;
            }else{
                    j++;
                }
        }
        
        return Arrays.copyOfRange(res, 0, k);
    }
}

 

 

代码部分三(2ms 99.99%)

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        
        int i = 0;
        int j = 0;
        int k = 0;
        while(i < len1 && j < len2){
            if(nums1[i] == nums2[j]){
                nums1[k] = nums2[j];
                k++;
                i++;
                j++;
            }else 
                if(nums1[i] < nums2[j]){
                    i++;
            }else{
                    j++;
                }
        }
        
        int[] res = new int[k];
        for(int x = 0; x < k; x++){
            res[x] = nums1[x];
        }
        return res;
    }
}