LeetCode-350-两个数组的交集 II

两个数组的交集 II

题目描述:给定两个数组,编写一个函数来计算它们的交集。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:数组遍历
  • 首先,声明一个Map为firstMap,其中key为出现的数字,value为相应数字出现的次数,然后遍历nums1,将数字和出现的次数初始化到firstMap中;
  • 然后,声明一个数组为result;
  • 然后遍历nums2中的数字,判断如果firstMap的key中包含该数字并且对应的次数大于0,则将这个数字放到result中。
  • 遍历完成后,返回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 + " ");
        }
    }
}

【每日寄语】 用你的笑容去改变这个世界,别让这个世界改变了你的笑容。

posted @ 2021-09-23 11:11  醉舞经阁  阅读(27)  评论(0编辑  收藏  举报