今天練習基礎題Two Sum
題目:給一個整數陣列 nums 和一個目標值 target,找出陣列中兩個數字的索引,讓它們相加等於 target。
https://ithelp.ithome.com.tw/upload/images/20250918/20169339yoCLWZR259.jpg
我們利用Python來解題
解法一
https://ithelp.ithome.com.tw/upload/images/20250918/20169339hub5uJKohZ.jpg
列舉所有組合檢查
寫法簡單、直覺
大陣列慢
解法二(優化版)
https://ithelp.ithome.com.tw/upload/images/20250918/20169339T2C3RbSvd4.jpg
遍歷一次,用字典快速查找差值
快速、高效
多了額外空間