0349-Intersection of Two Arrays

題目如下:

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

只求 pass 的解答。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
func intersection(nums1 []int, nums2 []int) []int {
	m := make(map[int]int)
	for _, n1 := range nums1 {
		if _, has := m[n1]; !has {
			m[n1] = 1
		}
	}
	var result []int
	for _, n2 := range nums2 {
		if v, has := m[n2]; has && v == 1 {
			m[n2] = 2
			result = append(result, n2)
		}
	}
	return result
}

過去曾用 python 寫的解法,能用一行也太神奇了。而且語法很數學,難怪大家都愛用 python

1
2
3
4
5
6
7
8
class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        return list(set([x for x in nums1 for y in nums2 if x == y]))
updatedupdated2021-05-172021-05-17