> For the complete documentation index, see [llms.txt](https://junnie.gitbook.io/nine-chapter/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://junnie.gitbook.io/nine-chapter/6.array/547intersection-of-two-arrays.md).

# 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**

Given*nums1*=`[1, 2, 2, 1]`,*nums2*=`[2, 2]`, return`[2]`.

## 2.Code

Version 1: HashSet

```
 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;           
    }
```

Version 2： Sort + Binary Search

Version 3： Sort+ Merge

<http://www.jiuzhang.com/solutions/intersection-of-two-arrays/>
