Short understandable O(n) solution in Swift - Using a dictionary (hash table)


  • 1
    D
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        var dick:[Int:Int] = [:]
        var result:[Int] = []
        for i in 0..<nums.count{
            if let index = dick[nums[i]]{
                result.append(i)
                result.append(index)
            }else{
                let matchingValue = target - nums[i]
                dick[matchingValue] = i
            }
        }
        return result
    }
    

Log in to reply
 

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