原題
349. 兩個數組的交集 - 力扣(LeetCode)
給定兩個數組?nums1
?和?nums2
?,返回?它們的?交集?。輸出結果中的每個元素一定是?唯一?的。我們可以?不考慮輸出結果的順序?。
示例 1:
輸入:nums1 = [1,2,2,1], nums2 = [2,2] 輸出:[2]
示例 2:
輸入:nums1 = [4,9,5], nums2 = [9,4,9,8,4] 輸出:[9,4] 解釋:[4,9] 也是可通過的
解答
兩個數組的交集就是要兩個數組相同的元素,因為java的HashSet不能存儲重復的元素,所以適合用在這道題。
class Solution {public int[] intersection(int[] nums1, int[] nums2) {if(nums1.length==0 || nums2.length==0){return new int[0];}HashSet<Integer> n=new HashSet<>();for(int num : nums1){n.add(num);}HashSet<Integer> hash=new HashSet<>();for(int i=0;i<nums2.length;i++){if(n.contains(nums2[i])){hash.add(nums2[i]);//如果這里不用HashSet存儲的話相同的數字可能會出現多次}}int[] result=new int[hash.size()];int count=0;Iterator<Integer> iterator=hash.iterator();//迭代器遍歷while(iterator.hasNext()){result[count++]=iterator.next();}return result;}
}