# 349. Intersection of Two Arrays

![](/files/-Mfx0BZomP4CI-tkDR83)

## find intersection, use set, this one is better

time: O(n)

space: O(n)

```java
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        // first instinction, use hashset, add data, find duplicate, add to array
        Set<Integer> set = new HashSet<>();
        List<Integer> list = new ArrayList<>();

        for (int num : nums1) {
            set.add(num);
        }
        for (int num : nums2) {
            if (set.contains(num)) {
                list.add(num);
                set.remove(num);
            }
        }
        return list.stream().mapToInt(n -> n).toArray();
    }
}
```

## sort first, then use binary search, find and add into set, this is another thought, but time complexity is not good.

time: O(nlogn)

space: O(n)

```java
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> res = new HashSet<>();
        Arrays.sort(nums1);
        for (int num : nums2) {
            if (bs(nums1, num)) {
                res.add(num);
            }
        }
        int[] result = new int[res.size()];
        int i = 0;
        for (int num : res) {
            result[i++] = num;
        }
        return result;
    }
    private boolean bs(int[] nums, int num) {
        int start = 0;
        int end = nums.length-1;
        while (start + 1 < end) {
            int mid = start + (end - start)/2;
            if (nums[mid] < num) {
                start = mid;
            } else {
                end = mid;
            }
        }
        if (nums[start] == num) {
            return true;
        }
        if (nums[end] == num) {
            return true;
        }
        return false;
    }
}
```

## JS

```javascript
/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersection = function(nums1, nums2) {
    const set = new Set(nums1);
    
    return [...new Set(nums2.filter(n => set.has(n)))];
};
```


---

# 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://timmybeeflin.gitbook.io/cracking-leetcode/binary-search/349.-intersection-of-two-arrays.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.
