Accepted Swift solution in O(n)

  • 1

    Here is my accepted Swift solution with O(n) complexity and only one iteration of the array.

    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
            var dict = [Int: Int]()
            for (i, num) in nums.enumerated() {
                if let index = dict[target-num] {
                    if i != index {
                        return [index, i]
                dict[num] = i

Log in to reply

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