Swift solution


  • 0
    V
    class Solution {
        func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
            
            var hash: [Int : Int] = [:]
            var res : [Int] = [];
            
            for (i, n) in nums.enumerated() {
                if let index = hash[target - n]{
                    res.append(index)
                    res.append(i)
                }
                hash[n] = i 
            }
            return res;
        }
    }
    
    

  • 0
    T

    @vonnass, interesting solution!
    My suggestion is to add "break" after "res.append(i)"; there is no need to iterate after that


Log in to reply
 

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