LeetCode - 349. Intersection of Two Arrays

題目:

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

思路與步驟:

得相同元素,只要挨個比較即可。爲了不用雙重循環,想到用 contains() 直接判斷可以省掉一個循環。由於不出現重複的,所以想到 HashSet


編程實現:

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<Integer>();
        for(int num : nums1)    set1.add(num);
        
        List<Integer> intersectionList = new ArrayList<Integer>();
        for(int i=0; i<nums2.length; i++)
            if(set1.contains(nums2[i])){
                intersectionList.add(nums2[i]);
                set1.remove(nums2[i]);
            }
            
        int[] result = new int[intersectionList.size()];
        for(int i=0; i<intersectionList.size(); i++)    result[i] = intersectionList.get(i);
        return result;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章