Solution in Go (9ms) using sort and two pointers


  • 0
    func intersection(nums1, nums2 []int) []int {
        result := []int{}
        sort.Ints(nums1)
        sort.Ints(nums2)
        i, j := 0, 0
        for i < len(nums1) && j < len(nums2) {
            if nums1[i] < nums2[j] {
                i++
            } else if nums1[i] > nums2[j] {
                j++
            } else {
                if (i == 0 || nums1[i] != nums1[i - 1] &&
                    j == 0 || nums2[j] != nums2[j - 1]) {
                    result = append(result, nums1[i])
                }
                i++
                j++
            }
        }
        return result
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.