1. Two Sum
題目網址:https://leetcode.cn/problems/two-sum/
題意:給一 array
nums和一整數target, 求nums中兩數和剛好為target之 index, 假設每一種target只會對應到一組解。注意:同一個元素不可重複使用, 可按照任意順序返回。

Solution:
想法:利用 hash table, 由於題目保證一定有解, 因此對
nums[i]而言, 先去 hash table 中找target - nums[i]是否存在
- 若存在, 則直接返回
- 否則, 將
nums[i]還有其index加入到 hash table 中
class Solution { |
- time:$O(n)$ ➔ 遍歷
nums - space:$O(n)$ ➔
umap的元素個數不超過n
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Zako's Blog!
評論