【leetode】349. Intersection of Two Arrays

来源:互联网 发布:淘宝过期化妆品 编辑:程序博客网 时间:2024/06/06 10:45

题目要求:

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.
即求两个数组的交集

思路:通过一个set来记录两个数组中相同的元素,最后把set转为数组

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {         HashSet<Integer> hashSet = new HashSet<Integer>();        for(int i=0;i<nums1.length;i++)        {            for(int j=0;j<nums2.length;j++)            {                if(nums1[i]==nums2[j])                {                    if(hashSet.contains(nums1[i]))                    {                        continue;                    }else{                        hashSet.add(nums1[i]);                    }                }            }        }        int[] intersection = new int[hashSet.size()];        int h=0;        Iterator<Integer> it = hashSet.iterator();        while(it.hasNext())        {            intersection[h]=it.next();            h++;        }        return intersection;    }}


0 0
原创粉丝点击