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;
    }
}

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