My Swift solution in O(n) time


  • 1
    A
    class Solution {
        func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
            var map = [Int: Int]()
            for (i, n) in nums.enumerated() {
                if let idx = map.index(forKey: target - n) {
                    return [map[idx].value, i]
                } else {
                    map[n] = i
                }
            }
            return []
        }
    }
    

  • 0
    Z

    I think you mean O(n*log(n)). Found a similar solution.

    func sumTow(nums: [Int], target: Int)->[Int]{
            var dict = [Int:Int]()
            for (i, num) in nums.enumerated() {
                if let n = dict[target-num] {
                    return [n , i]
                }
                dict[num] = i
            }
            return []
        }
    

Log in to reply
 

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