TwoSum Swift Solution - TagMerge
3TwoSum Swift SolutionTwoSum Swift Solution

TwoSum Swift Solution

Asked 10 months ago
2
3 answers

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.

Source: link

1

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].

Source: link

0

In Sweeper's excellent answer, he explained what dict is used for: It lets you use a value from the array to find that value's index. It would be more obvious what the dictionary was used for if we called it indexes, and this code builds the same dictionary in a more explicit way:

var indexes = [Int: Int]()

for index in 0..<array.count {
    let value = array[index]
    indexes[value] = index
}

After that, you get a dictionary:

[2:0, 7:1, 11:2, 15:3]

You could write the function this way:

func twoSum(_ array: [Int], _ target: Int) -> [Int] {
    var indexes = [Int: Int]()

    for index in 0..<array.count {
        let value = array[index]
        indexes[value] = index
    }

    for index in 0..<array.count {
        let value = array[index]
        if let otherIndex = indexes[target - value],
           index != otherIndex {
            return [index, otherIndex]
        }
    }
    fatalError("Unable to match values")
}

That is a much more long-winded (and less efficient) way of doing the same thing. It loops through the array twice instead of once, but the results should be the same.

Source: link

Recent Questions on swift

    Programming Languages