[LeetCode] NO. 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].

[题目解析] 这是一个很简单的求交集的问题,可以用Set来解决。如下。

    public static int[] intersection(int[] nums1, int[] nums2){        
        Set<Integer> set = new HashSet<Integer>();
        Set<Integer> interset = new HashSet<Integer>();
        for(int num : nums1){
            set.add(num);
        }
        for(int num : nums2){
            if(set.contains(num)){
                interset.add(num);
            }
        }
        int result[] = new int[interset.size()];
        int j = 0;
        for(Integer num : interset){
            result[j++] = num;
        }
        return result;
    }

 

posted @ 2016-08-14 18:01  三刀  阅读(125)  评论(0编辑  收藏  举报