leetcode349. 两个数组的交集
生活随笔
收集整理的這篇文章主要介紹了
leetcode349. 两个数组的交集
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
給定兩個數(shù)組,編寫一個函數(shù)來計算它們的交集。
示例 1:
輸入: nums1 = [1,2,2,1], nums2 = [2,2]
輸出: [2]
示例 2:
輸入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
輸出: [9,4]
說明:
輸出結(jié)果中的每個元素一定是唯一的。
我們可以不考慮輸出結(jié)果的順序。
思路:
把一個數(shù)組的數(shù)字放set里,遍歷另一個數(shù)組判斷在不在set里即可。
class Solution {public int[] intersection(int[] nums1, int[] nums2) {Set<Integer> set = new HashSet<>();int minLen = Math.min(nums1.length, nums2.length);int[] res = new int[minLen];for(int num : nums1){set.add(num);}int k = 0;for(int num : nums2){if(set.contains(num)){res[k++] = num;set.remove(num);} }return Arrays.copyOf(res, k);} }?
總結(jié)
以上是生活随笔為你收集整理的leetcode349. 两个数组的交集的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 堆应用例题三连
- 下一篇: leetcode326. 3的幂 如此6