題目


給予一個任意陣列(nums)與一個目標數字(target),回傳陣列中的兩個index,其值可以相加後等於目標數字

<aside> ⚠️ 假設答案只會有一種,而且不能重複回傳同一個index

</aside>

範例


解題想法


<aside> ⚠️ 在不確定陣列長度下,我先取得該陣列的第一個數字(假設稱num),其元素對應排序叫index,有了第一個數字,就可能target回推第二個數字該是多少,這邊要去確認這個數字是否有在陣列(nums)裏面,有的話則代表你找到解答,沒有的話則做下一次迭代去取得第二個數字與第二個index再回推

</aside>

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 []
}

LeetCode


Two Sum - LeetCode