LeetCode 349. Intersection of Two Arrays(数组交集)

来源:互联网 发布:线刷宝刷机有垃圾软件 编辑:程序博客网 时间:2024/06/04 23:28

原题网址:https://leetcode.com/problems/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.

方法:通过集合求交集。

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

0 0
原创粉丝点击