leetcode初级算法4.两个数组的交集 II
仅为个人刷题记录,不提供解题思路
题解与收获
我的解法:(总结在代码中)
public int[] intersect(int[] nums1, int[] nums2) {//为空则返回if(nums1 == null || nums2 == null){return null;}//先用较短的数组进行map插入操作if(nums1.length > nums2.length){return intersect(nums2,nums1);}HashMap<Integer,Integer> map = new HashMap<>();//遍历nums1数组得到for (int num : nums1) {int count = map.getOrDefault(num,0) + 1;map.put(num, count);}//新建数组准备储存相同的元素int[] intersection = new int[nums1.length];//表示新数组的起始点int index = 0;//遍历nums2数组,遍历出一个就将对应的value减1for (int num : nums2) {int count = map.getOrDefault(num,0);if(count > 0){intersection[index++] = num;count--;if(count > 0){map.put(num,count);}else{map.remove(num);}}}//裁剪数组(需要熟练应用数组的API)return Arrays.copyOfRange(intersection,0,index);}
后记:难点在于,利用HashMap的value影射两个数组中重复的元素个数,重复一次count–一次,同时将该元素插入新数组中,最后调用Arrays.copyOfRange得到裁剪后的数组!!!!!!!!!!