twoSum O(n) in Swift


  • 0
    F
    class Solution {
        func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
            var numDictionary = [Int:Int]()
        
            if nums.isEmpty{
                return [0]
            }
        
            for index in 0...nums.count-1{
                if numDictionary.keys.contains(nums[index]){
                    return [numDictionary[nums[index]]!, index]
                }else{
                    numDictionary[target - nums[index]] = index
                }
            }
            
            return [0]
        }
    }
    

Log in to reply
 

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