> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/01-19-2022-350.md).

# 01/19/2022 350

![](/files/fn5kaHLbBkORW55LklGJ)

method 1:

sort nums1 and nums2. Initialize int i, j, k = 0. Move indices `i` along `nums1`, and `j` through `nums2`: if nums1\[i] < nums2\[j], i++; else if nums1\[i] > nums2\[j], j++; else nums1\[k] = nums1\[i], i++, j++. Then finally return the copy of the nums1 with the range from 0 to k.&#x20;

Time Complexity: O(nlogn+mlogm)

Space: from O(logn+logm) to O(n+m),

![](/files/8cCMb1fLtPxjwXUkRaqJ)

method 2:\
using hashmap to put the element and its counts in nums1. Then test if the counts of each element of nums2 in the nums1 > 0. If it is, then set nums1\[i++] = it and set the count of it in the map - 1.&#x20;

Time O(n + m)

Space O(min(n,m))

class Solution { public int\[] intersect(int\[] nums1, int\[] nums2) {

```
   if(nums1.length > nums2.length) return intersect(nums2, nums1);//need to remember
   
   HashMap<Integer, Integer> map = new HashMap<>();
   for(int n: nums1){
       map.put(n, map.getOrDefault(n, 0) + 1);
   }
   
   int i = 0;
   for(int n: nums2){
       int count = map.getOrDefault(n,0);
       if(count > 0){
           nums1[i++] = n;
           map.put(n, count - 1);               
       }
    }
   return Arrays.copyOfRange(nums1, 0, i);
   
```

} }
