# 548.Intersection of Two Arrays II

## 1.Description(Easy)

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

### Notice

* Each element in the result should appear as many times as it shows in both arrays.
* The result can be in any order.

**Example**

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

## 2.Code

Version 1: HashMap (Time exceed)

```
public int[] intersection(int[] nums1, int[] nums2) {
        if(nums1==null || nums2==null){
            return null;
        }
        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
        for(int i=0;i<nums1.length;i++){
            if(!map.containsKey(nums1[i])){
                map.put(nums1[i], 1);
            }else{
                map.put(nums1[i],map.get(nums1[i])+1);
            }
        }

        ArrayList<Integer> list=new ArrayList<Integer>();
        for(int i=0;i<nums2.length;i++){
            if(map.containsKey(nums2[i]) && map.get(nums2[i])>0){
                list.add(nums2[i]);
                map.put(nums2[i], map.get(nums2[i])-1);
            }
        }

        int[] result=new int[list.size()];
        for(int i=0;i<list.size();i++){
            result[i]=list.get(i);
        }
        return result;
    }
```

Version 2: Sort+Two pointer

```
public int[] intersection2(int[] nums1, int[] nums2){
        if(nums1==null || nums2==null){
            return null;
        }
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int index1=0;
        int index2=0;
        ArrayList<Integer> list=new ArrayList<Integer>();
        while(index1<nums1.length && index2<nums2.length){
            if(nums1[index1]>nums2[index2]){
                index2++;
            }else if(nums1[index1]<nums2[index2]){
                index1++;
            }else{
                list.add(nums1[index1]);
                index1++;
                index2++;
            }

        }
        int[] result=new int[list.size()];
        for(int i=0;i<list.size();i++){
            result[i]=list.get(i);
        }
        return result;
    }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://junnie.gitbook.io/nine-chapter/6.array/548intersection-of-two-arrays-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
