2
头图

Intersection of two arrays II

Title description: Given two arrays, write a function to calculate their intersection.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution one: array traversal
  • First, declare a Map as firstMap, where key is the number that appears, value is the number of times the corresponding number appears, and then traverse nums1 to initialize the number and the number of times to firstMap;
  • Then, declare an array as result;
  • Then traverse the number in nums2, and determine if the number is contained in the key of firstMap and the corresponding number is greater than 0, then put this number in the result.
  • After the traversal is completed, all the numbers in the result are returned as the result.
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class LeetCode_350 {
    public static int[] intersect(int[] nums1, int[] nums2) {
        // 第一个数组中的数字以及出现的次数
        Map<Integer, Integer> firstMap = new HashMap<>();
        for (int i : nums1) {
            if (firstMap.containsKey(i)) {
                firstMap.put(i, firstMap.get(i) + 1);
            } else {
                firstMap.put(i, 1);
            }
        }

        int[] result = new int[nums1.length];
        int index = 0;
        for (int i : nums2) {
            if (firstMap.containsKey(i) && firstMap.get(i) > 0) {
                result[index++] = i;
                firstMap.put(i, firstMap.get(i) - 1);
            }
        }

        return Arrays.copyOfRange(result, 0, index);
    }

    public static void main(String[] args) {
        int[] nums1 = new int[]{1, 2, 2, 1}, nums2 = new int[]{2, 2};
        for (int i : intersect(nums1, nums2)) {
            System.out.print(i + " ");
        }
    }
}
[Daily Message] Use your smile to change the world, don't let this world change your smile.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!