Two Sum solution in Swift O(n)


  • 0
    L

    class Solution {
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    var dictionary = Int:Int
    for (index, element) in nums.enumerated() {
    dictionary[element] = index
    }
    for (index, element) in nums.enumerated() {
    if let value = dictionary[target - element], index != value {
    return [value, index]
    }
    }
    return []
    }
    }


Log in to reply
 

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