問題: TwoSums
整数の配列を渡された時、足したら答えがターゲットになる2つの数字の指数を返せ。
ルールとして、同じ数字を使ってはいけない。
例)
2つの数字, "2" と "7" を足すとターゲットになるので、
nums配列の索引 "0" と "1"を返す
nums = [2, 7, 11, 15]
target = 9
nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
ヒント!!
こんな関数で始めてみよう。
func twoSum(_ nums: [Int], _ target: Int) -> ((Int, Int))? {
}
答え例はこちら!
example1.swift
var arrayN = [1,4,5,6,8,9,11]
var target = 6
func twoSum(_ nums: [Int], _ target: Int) -> (Int, Int)? {
var dict = [Int: Int]()
for i in nums.indices {
if let newK = dict[nums[i]] {
return (newK, i)
} else {
dict[target - nums[i]] = i
print("Dictionary: \(dict)")
}
}
return nil // もし、2つの数字の合計がターゲットに見合わない場合はnilを返す。
}
print("Answer: \(String(describing: twoSum(arrayN, target)))")
メモ: dict[key,value] だとすると、key = target - num[i] で value = i
メモ: dict[nums[i]] が nilだった場合、 elseが実行される。
ループの(index,value)を使えばもっと楽かも。
example2.swift
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var dictionary = [Int:Int]()
for (i,value) in nums.enumerated() {
if let first = dictionary[value] {
return [first,i]
} else{
dictionary[target - value] = i
}
}
return [0]
}
答えとログ
xCodeのコンソールの値を見るとわかりやすいよ!こうすることで1巡するだけで、答えが割り出せるようになっている。
Dictionary: [5: 0]
Dictionary: [5: 0, 2: 1]
Answer: (0, 2)
Program ended with exit code: 0
コードの答えはRay Wenderlich さんから拝借しました。
https://github.com/raywenderlich/swift-algorithm-club/tree/master/Two-Sum%20Problem#two-sum-problem