- Time complexity O(n)
- Space complexity O(n)
- Time complexity O(nlogn)
- Space complexity O(1)
Note space complexity means the extra needed space, excluding input and output.
- If it is sorted, which is better?
- 2 pointers > hashmap
- If ask you return the indices of the two found elements, which is better?
- hashmap > 2 pointers
2 pointers just add | 2 pointers add and keep sorted | hashmap | |
---|---|---|---|
AddNumber | O(1) | O(n) | O(1) |
FindTwoSum | O(nlogn) | O(n) | O(n) |
- Just add: Time complexity O(1). (This is better for the situation wherer there are much more add than find.)
- Add and keep sorted: Insert sorting: O(n)
- Time complexity O(1)
- Just add in Add(): Time complexity O(nlogn)
- Add and keep sorted in Add(): O(n)
- Time complexity O(n)
- Time complexity O(logn) + O(n) = O(n)
- Search (find place to insert) O(logn)
- But insert O(n)
(Binary search is base on array, here just for discussion)
- Time complexity O(n) + O(1) = O(n)
- Search (find place to insert) O(n)
- But insert O(1)
- Heap is a tree structure. Elements are not sorted.
- Add/Insert O(logn)
- Find: need to get all elements (which takes O(nlogn)) and then put them all into a sorted array and then do two sum.
- Add O(logn)
- FindTwoSum O(n). Need firstly Inorder Traversal to get all elements (the result is sorted already) which takes O(n).