349. Intersection of Two Arrays

时间:2024-12-19 13:36:32

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) {
ArrayList<Integer> list=new ArrayList<>(); for(int i=0;i<nums1.length;i++)
{
for(int j=0;j<nums2.length;j++)
{
if(nums1[i]==nums2[j])
{
if(!list.contains(nums1[i]))
list.add(nums1[i]);
}
}
}
int[] result=new int[list.size()];
for(int i=0;i<list.size();i++)
result[i]=list.get(i);
return result;
}
}