func intersect(nums1 []int, nums2 []int) []int { resMap := make(map[int]int, len(nums1)) for _, v := range nums1 { if _, ok := resMap[v]; ok { resMap[v] += 1 } else { resMap[v] = 1 } } res := make([]int, 0, len(nums2)) for _, v := range nums2 { if _, ok := resMap[v]; ok && resMap[v] >= 1 { res = append(res, v) resMap[v] -= 1 } } return res }
双指针
优化:如果已经排好序,则减少排序次数
不能用if else, if else是顺序执行,前面++后,最后一层判断会超出slice边界
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
func intersect(nums1 []int, nums2 []int) []int { sort.Ints(nums1) sort.Ints(nums2) i, j := 0, 0 var res []int for i < len(nums1) && j < len(nums2) { switch { case nums1[i] < nums2[j]: i++ case nums1[i] > nums2[j]: j++ case nums1[i] == nums2[j]: res = append(res, nums1[i]) i++ j++ } } return res }