349. Intersection of Two Arrays
https://leetcode.com/problems/intersection-of-two-arrays
Python
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
Go
func intersection(nums1 []int, nums2 []int) []int {
// Covert nums2 into map, key as num2, value with true (whatever)
nums2Map := map[int]bool{}
for _, num2 := range nums2 {
nums2Map[num2] = true
}
// If num1 in nums2, append to resultMap
// Duplicate item will be overwrite
resultMap := map[int]bool{}
for _, num1 := range nums1 {
if _, exist := nums2Map[num1]; exist {
resultMap[num1] = true
}
}
// Covert resultMap back to []int
i := 0
result := make([]int, len(resultMap))
for num, _ := range resultMap {
result[i] = num
i++
}
return result
}