[LeetCode] 1. Two Sum [Easy]

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

Analyse:

由於題目假設必有一解, 故nums中的element之中必有一個A與B, 其A等於target - B.

在for迴圈中利用[Int: Int] Dictionary 儲存每個nums[i]的value與Index,

若找到一個nums[i]其 Dictionary [target - nums[i]] != nil 則為其解..

Solution:

class Solution {
    
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        var dictionary:[Int: Int] = [:]
        
        for i in 0..<nums.count {
            let value = target - nums[i];
            
            if(dictionary[value] != nil) {
                return [dictionary[value]!, i]
            }
            
            dictionary[nums[i]] = i;
            
        }
        
        return [];
    }
}

Last updated