problem
- 一維陣列中找出兩數相加等於target,並返回其索引
Solution
brute force
- 利用兩個index 分別指向兩個不同的數字,找尋哪兩個數字總和為 target
1 | class Solution { |
sorting
- 先排序,在用雙指標從排序後的陣列找出兩個元素其總和為target,再回原本陣列找出其索引。
1 | class Solution { |
hash table
- 利用hash table 紀錄出現過元素及其索引
1 | class Solution { |
analysis
- brute force
- time complexity
O(n^2)
- space complexity
O(1)
- time complexity
- sorting
- time complexity
O(nlogn)
- space complexity
O(n)
- time complexity
- hash table
- time complexity
O(n)
- space complexity
O(n)
- time complexity