Skip to content

Instantly share code, notes, and snippets.

@KrauserHuang
Last active April 25, 2022 02:37
Show Gist options
  • Save KrauserHuang/6bba4e50c0adf7eeb14c024185bb7a77 to your computer and use it in GitHub Desktop.
Save KrauserHuang/6bba4e50c0adf7eeb14c024185bb7a77 to your computer and use it in GitHub Desktop.
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
// 拿來儲存數字(Key)對應的index(Value)
var dict = [Int: Int]()
/*
nums.enumerated()結果
(0, 2)
(1, 7)
(2, 11)
(3, 15)
*/
for (index, num) in nums.enumerated() {
// 利用target回推第二個數字, anotherNum = 9 - 2 = 7
// 第二次遞迴anotherNum = 9 - 7 = 2
let anotherNum = target - num
// 從dict來確定anotherNum(7)這個Key是否存在,如果有,則代表你找到此兩個數字
// 但由於dict一開始是空的,所以第一次loop,該statement為false
// 第二次遞迴dict[2]是存在的,並取出anotherIndex(0),該index(0)不能重複於目前遞迴的index(1)
if dict[anotherNum] != nil, let anotherIndex = dict[anotherNum], anotherIndex != index {
// 條件達成回傳[dict[2] = 0, index = 1]
return [anotherIndex, index]
} else {
// 若該dict不錯在anotherNum(7)這個Key,則將num與index存入dict裡面,所以目前dict為[2, 0]
dict[num] = index
}
// 全部遞迴完一輪仍沒找到則代表input/output題目不match,回傳空的陣列
return []
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment