两个数组的交加 II

题目形容:给定两个数组,编写一个函数来计算它们的交加。

示例阐明请见LeetCode官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:数组遍历
  • 首先,申明一个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 + " ");        }    }}
【每日寄语】 用你的笑容去扭转这个世界,别让这个世界扭转了你的笑容。