547.Intersection of Two Arrays

1.Description(Easy)

Given two arrays, write a function to compute their intersection.

Notice

  • Each element in the result must be unique.

  • The result can be in any order.

Example

Givennums1=[1, 2, 2, 1],nums2=[2, 2], return[2].

Challenge

Can you implement it in_three_different algorithms?

2.Code

 public int[] intersection(int[] nums1, int[] nums2) {
        if(nums1==null || nums2==null){
            return null;
        }

        HashSet<Integer> set=new HashSet<Integer>();
        for(int i=0;i<nums1.length;i++){
            set.add(nums1[i]);
        }

        HashSet<Integer> result=new HashSet<Integer>();
        for(int i=0;i<nums2.length;i++){
            if(set.contains(nums2[i]) && !result.contains(nums2[i])){
                result.add(nums2[i]);
            }
        }

        int len=result.size();
        int[] section=new int[len];
        int index=0;
        for(Integer element : result){
            section[index++]=element;
        }
        return section;          
    }

Last updated