Swift solution


  • 0
    O

    One way to do is using set operations and conversions:

    func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
            return Array(Set(nums1).intersection(Set(nums2)))
    

    We can also use one set and a loop. This one looks like you coded more stuff:

    func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
            var num1Set = Set(nums1)
            var resultArray = [Int]()
            for num in nums2 {
                if num1Set.contains(num) {
                    resultArray.append(num)
                    num1Set.remove(num)
                    if num1Set.count == 0 {
                        break
                    }
                }
            }
            return resultArray
        }
    

Log in to reply
 

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