leetcode初级算法4.两个数组的交集 II
生活随笔
收集整理的這篇文章主要介紹了
leetcode初级算法4.两个数组的交集 II
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
leetcode初級(jí)算法4.兩個(gè)數(shù)組的交集 II
僅為個(gè)人刷題記錄,不提供解題思路
題解與收獲
我的解法:(總結(jié)在代碼中)
public int[] intersect(int[] nums1, int[] nums2) {//為空則返回if(nums1 == null || nums2 == null){return null;}//先用較短的數(shù)組進(jìn)行map插入操作if(nums1.length > nums2.length){return intersect(nums2,nums1);}HashMap<Integer,Integer> map = new HashMap<>();//遍歷nums1數(shù)組得到for (int num : nums1) {int count = map.getOrDefault(num,0) + 1;map.put(num, count);}//新建數(shù)組準(zhǔn)備儲(chǔ)存相同的元素int[] intersection = new int[nums1.length];//表示新數(shù)組的起始點(diǎn)int index = 0;//遍歷nums2數(shù)組,遍歷出一個(gè)就將對(duì)應(yīng)的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);}}}//裁剪數(shù)組(需要熟練應(yīng)用數(shù)組的API)return Arrays.copyOfRange(intersection,0,index);}后記:難點(diǎn)在于,利用HashMap的value影射兩個(gè)數(shù)組中重復(fù)的元素個(gè)數(shù),重復(fù)一次count–一次,同時(shí)將該元素插入新數(shù)組中,最后調(diào)用Arrays.copyOfRange得到裁剪后的數(shù)組!!!!!!!!!!
總結(jié)
以上是生活随笔為你收集整理的leetcode初级算法4.两个数组的交集 II的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阿凡题电脑版(阿凡题最新版下载)
- 下一篇: nba2k14平板电脑下载(NBA2k1