Swift solution - Hash Table


  • 0
    class Solution {
        func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
            var result = [Int](repeatElement(0, count: 2))
            var map = [Int: Int]()
            
            for i in 0..<nums.count {
                if map.keys.contains(target - nums[i]) {
                    result[1] = i
                    result[0] = map[target - nums[i]]!
                    return result
                }
                map[nums[i]] = i
            }
            
            return result
        }
    }
    

Log in to reply
 

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