> 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-14-2022-349.md).

# 01/14/2022 349

brutal force: initiate an array with the minimal size of nums1 and nums2. traverse each array and check if num1\[i] == nums\[k]. if it is true, set the boolean isunique = true. then check if this value has existed in the intersect array. If it is not, then add it into the intersect array. Finally, shrink the intersect array.

Time O(n \*m) Space O(min (n,m)

```
public int[] intersection(int[] nums1, int[] nums2) {
  int[] intersect = new int[Math.min(nums1.length, nums2.length)];
  int index = 0;
  for (int i = 0; i < nums1.length; i++) {
    for (int j = 0; j < nums2.length; j++) {
      if (nums1[i] == nums2[j]) {
        boolean isUnique = true;
        for (int k = 0; k < index; k++) {
          if (nums1[i] == intersect[k]) {
            isUnique = false;
          }
        }
        if (isUnique) {
          intersect[index++] = nums1[i];   
        }
      }
    }
  }
  int[] result = new int[index];
  for (; index-1 >= 0; index--) {
    result[index-1] = intersect[index-1];
  }
  return result;
}

```

brutal force optimization

class Solution {&#x20;

public int\[] intersection(int\[] nums1, int\[] nums2) {

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

    int[] result = new int[set.size()];
    int index = 0;
    
    for(int ele: set){
        result[index++] = ele;
    }
 
    
     return result;
 
}
```

}

using Hashset. Add nums1 value into a HashSet. Then initialize an arraylist list. loop through nums2, if set contains the number, add it into list and remove this number from the set. finally convert list to an array.

Time O(n + m)

Space O(n +m) for the worst case.

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

```
    HashSet<Integer> set = new HashSet<>();
    for(Integer n: nums1) set.add(n);
    
    List<Integer> list = new ArrayList<>();
    for(Integer n: nums2){
        if(set.contains(n)){
            list.add(n);
            set.remove(n);
        }
    }
    int[] result = new int[list.size()];
    int i = 0;
    for(int n: list) result[i++] = n;
    
    return result;
   
 
}
```

}
