leetCode 两个数组的交集 II 问题记录
生活随笔
收集整理的這篇文章主要介紹了
leetCode 两个数组的交集 II 问题记录
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
問題如下:
給定兩個數(shù)組,寫一個方法來計算它們的交集。例如: 給定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].注意:輸出結果中每個元素出現(xiàn)的次數(shù),應與元素在兩個數(shù)組中出現(xiàn)的次數(shù)一致。我們可以不考慮輸出結果的順序。 跟進:如果給定的數(shù)組已經排好序呢?你將如何優(yōu)化你的算法? 如果 nums1 的大小比 nums2 小很多,哪種方法更優(yōu)? 如果nums2的元素存儲在磁盤上,內存是有限的,你不能一次加載所有的元素到內存中,你該怎么辦??
自己的解法:
class Solution {public int[] intersect(int[] nums1, int[] nums2) {HashMap<Integer,Integer> hashMap = new HashMap<>();ArrayList<Integer> result = new ArrayList<>();if (nums1.length > 0){for (int i =0;i<=nums1.length-1;i++){Integer temp = hashMap.get(nums1[i]);if (temp == null){hashMap.put(nums1[i],1);}else {hashMap.put(nums1[i],temp+1);}}for(int j=0;j<=nums2.length-1;j++){Integer temp = hashMap.get(nums2[j]);if (temp != null){result.add(nums2[j]);if (temp> 1){hashMap.put(nums2[j],temp-1);}else {hashMap.remove(nums2[j]);}}}}Integer[] integers = new Integer[result.size()];result.toArray(integers);int tmpInt[] = new int[result.size()];for (int i = 0; i < integers.length; i++) {tmpInt[i] = integers[i];}return tmpInt;} }?
思路: 1.先遍歷數(shù)組1,將數(shù)組的每一項存入一個hashMap,如果一個元素出現(xiàn)多次則hashmap的value+1
? ? ? ? ? 2.遍歷數(shù)組2,判斷當前元素在hashmap中是否存在,如果存在就將這個元素加入到result中
? ? ? ? ? 3.判斷當前元素的value,如果大于1則減1,否則將這個元素的key從hash中移除,
? ? ? ? ? 4.最終得到的就是所求的兩個數(shù)組重復的部分
?
leet給的最優(yōu)解
class Solution {public int[] intersect(int[] nums1, int[] nums2) {int len1 = nums1.length;int len2 = nums2.length;int len = len1 > len2 ? len2 : len1;Arrays.sort(nums1);Arrays.sort(nums2);int[] nums = new int[len];int k = 0;int curr1, curr2 = 0;for(int i = 0, j = 0; i < len1 && j < len2;) {curr1 = nums1[i];curr2 = nums2[j];if(curr1 == curr2) {nums[k] = curr1;k += 1;i += 1;j += 1;} else if(curr1 < curr2) {i += 1;} else {j += 1;}}return Arrays.copyOfRange(nums, 0, k); } }?
嘗試理解一下思路:
1.找到兩個數(shù)組中相對較短的哪一個
2.對兩個數(shù)組進行排序
3.從0開始遍歷兩個數(shù)組,判斷當前遍歷到的數(shù)組1和數(shù)組2元素是否相等,如果相等表示兩個數(shù)組重復的部分開始,將這個元素放在返回數(shù)組中指示標志k所在的位置然后k+1
4.遍歷玩兩個數(shù)組后對返回數(shù)組進行截取,得到重復部分的數(shù)組
轉載于:https://www.cnblogs.com/beliveli/p/9015085.html
總結
以上是生活随笔為你收集整理的leetCode 两个数组的交集 II 问题记录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hdu 4336 Card Collec
- 下一篇: WEB请求处理