題目描述
??給你兩個下標從 0 開始的整數數組 nums1 和 nums2 ,請你返回一個長度為 2 的列表 answer ,其中:answer[0] 是 nums1 中所有 不 存在于 nums2 中的 不同 整數組成的列表。answer[1] 是 nums2 中所有 不 存在于 nums1 中的 不同 整數組成的列表。注意:列表中的整數可以按 任意 順序返回。
解析
??正常解法就是用兩個set去存儲然后相互找滿足條件的元素,手動循環比使用removeAll快一點。
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {List<List<Integer>> res = new ArrayList<>();List<Integer> temp1 = new ArrayList<>();List<Integer> temp2 = new ArrayList<>();Set<Integer> set1 = new HashSet<>();Set<Integer> set2 = new HashSet<>();for(int n : nums1) {set1.add(n);}for(int n : nums2) {set2.add(n);}for(int s : set1) {if(!set2.contains(s)){temp1.add(s);}}res.add(temp1);for(int s : set2) {if(!set1.contains(s)){temp2.add(s);}}res.add(temp2);return res;}
??然后就是巧妙的解法了,由于提示中有說明輸入的-1000 <= nums1[i], nums2[i] <= 1000,且1 <= nums1.length, nums2.length <= 1000,那么說明nums中的元素最大值最小值之差最多2000,因此可以定義一個2000長度的數組來記錄每個元素出現的次數。
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {List<List<Integer>> resultList = new ArrayList<>();List<Integer> list1 = new ArrayList<>();List<Integer> list2 = new ArrayList<>();int[] common = new int[2001];for (int i : nums1) {common[i + 1000] = 1;}for (int i : nums2) {if (common[i + 1000] == 0) {list2.add(i);}common[i + 1000]++;}for (int i : nums1) {if (common[i + 1000] == 1) {list1.add(i);}common[i + 1000]++;}resultList.add(list1);resultList.add(list2);return resultList;}