TwoSum Swift Solution

I just started learning coding with swift, and was trying TwoSum.

"Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]."

I found some solutions from GitHub that I cannot understand.

code is from https://github.com/soapyigu/LeetCode-Swift/blob/master/Array/TwoSum.swift

class TwoSum {
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        var dict = [Int: Int]()

        for (i, num) in nums.enumerated() {
            if let lastIndex = dict[target - num] {
                return [lastIndex, i]
            }
            dict[num] = i
        }
        fatalError("No valid outputs")
    }
}

Could someone be so kind to explain to codes. Thanks a lot.


Solution 1:

The dict initialised in the method stores the numbers in the input as keys, and their indices as values. The program uses this to remember which number is where. The dict can tell you things like "the number 2 is at index 0".

For each number num at index i in the input array, we subtract num from the target to find the other number that we need, in order for them to add up to target.

Now we have the other number we need, we check to see if we have seen such a number before, by searching dict. This is what the if let lastIndex = dict[target - num] part is doing. If the dict knows what index the other number is at, we return that index, and i.

If we haven't seen that number before, we record i into the dictionary under the key num, hoping that in later iterations, we can find a number that when added to num, makes 9.

Solution 2:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

var arr:[Int] = []
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    var toggle = false
    for i in 0..<nums.count {
        for j in i+1..<nums.count {
            if toggle == false {
                if(nums[i]+nums[j]==target){
                    toggle = true
                    arr.insert(i, at: 0)
                    arr.insert(j, at: 1)
                    break
                }
            }
        }
    }
    return arr
}

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].