Swift O(n) solution (One pass) - 28ms


  • 0
    Z

    This solution is pretty short and easy to read.
    Worst case scenario is O(n) I believe, which is one full iteration through the array.

    class Solution {
        var numDict = [Int : Int]()
        func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        
            for (index, firstNum) in nums.enumerated() {
                let secondNum = target - firstNum
                if numDict[secondNum] != nil {
                    return [numDict[secondNum]!, index]
                } else {
                    numDict[firstNum] = index
                }
            }
        
            return [-1]   // Return a clearly incorrect value if we don't find a match. Alternatively, you can make the function throw an error here.
        }
    }
    

    Edit: Moving the numDict var to the class instead of inside of the function seems to improve the runtime by 50% (Though I don't see why this would be the case here.)


Log in to reply
 

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