你的位置:首页 > Java教程

[Java教程]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].

Note:

    • Each element in the result must be unique.
    • The result can be in any order.

代码如下:

 1 public class Solution { 2   public int[] intersection(int[] nums1, int[] nums2) { 3     ArrayList<Integer> list=new ArrayList<>(); 4  5     for(int i=0;i<nums1.length;i++) 6     { 7       for(int j=0;j<nums2.length;j++) 8       { 9       if(nums1[i]==nums2[j])10       {11         if(!list.contains(nums1[i]))12         list.add(nums1[i]);13       }14       }15     }16     int[] result=new int[list.size()];17     for(int i=0;i<list.size();i++)18     result[i]=list.get(i);19     return result;20   }21 }