349. Intersection of Two Arrays

原题链接:https://leetcode.com/problems/intersection-of-two-arrays/description/
实现如下:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(Arrays.toString(s.intersection(new int[]{1, 2, 2, 1}, new int[]{2, 2})));
    }

    /**
     * 看到这道题目我首先想到的是直接使用哈希表,然后看了下 Related Topics:Hash Table, Two Pointers, Binary Search, Sort。里面确实
     * 提到了哈希表
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null) {
            return new int[0];
        }
        Set<Integer> set1 = new HashSet<>(nums1.length);
        for (int i = 0; i < nums1.length; i++) {
            set1.add(nums1[i]);
        }
        Set<Integer> set2 = new HashSet<>(nums2.length);
        for (int i = 0; i < nums2.length; i++) {
            if (set1.contains(nums2[i])) {
                set2.add(nums2[i]);
            }
        }
        int[] res = new int[set2.size()];
        int i = 0;
        for (int item : set2) {
            res[i++] = item;
        }
        return res;
    }

}
posted @ 2018-04-09 12:17  optor  阅读(118)  评论(0编辑  收藏  举报