日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetCode 两个数组的交集 II 问题记录

發布時間:2025/5/22 编程问答 12 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetCode 两个数组的交集 II 问题记录 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題如下:

給定兩個數組,寫一個方法來計算它們的交集。例如: 給定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].注意:輸出結果中每個元素出現的次數,應與元素在兩個數組中出現的次數一致。我們可以不考慮輸出結果的順序。 跟進:如果給定的數組已經排好序呢?你將如何優化你的算法? 如果 nums1 的大小比 nums2 小很多,哪種方法更優? 如果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.先遍歷數組1,將數組的每一項存入一個hashMap,如果一個元素出現多次則hashmap的value+1

? ? ? ? ? 2.遍歷數組2,判斷當前元素在hashmap中是否存在,如果存在就將這個元素加入到result中

? ? ? ? ? 3.判斷當前元素的value,如果大于1則減1,否則將這個元素的key從hash中移除,

? ? ? ? ? 4.最終得到的就是所求的兩個數組重復的部分

?

leet給的最優解

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.找到兩個數組中相對較短的哪一個

  2.對兩個數組進行排序

  3.從0開始遍歷兩個數組,判斷當前遍歷到的數組1和數組2元素是否相等,如果相等表示兩個數組重復的部分開始,將這個元素放在返回數組中指示標志k所在的位置然后k+1

  4.遍歷玩兩個數組后對返回數組進行截取,得到重復部分的數組

轉載于:https://www.cnblogs.com/beliveli/p/9015085.html

總結

以上是生活随笔為你收集整理的leetCode 两个数组的交集 II 问题记录的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。