問題如下:
給定兩個數組,寫一個方法來計算它們的交集。 例如: 給定 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.遍歷玩兩個數組后對返回數組進行截取,得到重復部分的數組