leetcode 349. Intersection of Two Arrays

来源:互联网 发布:java erp系统 编辑:程序博客网 时间:2024/06/14 00:46

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.

Subscribe to see which companies asked this question


思考:求两个数组的交集, 要求去重;


public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> countSet = new HashSet<>();
        Set<Integer> finalSet = new HashSet<>();
        for(int num : nums1){
            countSet.add(num);
        }
        for(int num : nums2){
            if(countSet.contains(num)){
                finalSet.add(num);
            }
        }
        int[] ret = new int[finalSet.size()];
        int i = 0;
        for(int num : finalSet){
            ret[i++] = num;
        }
        return ret;
    }
}

0 0