Two Sum III - Data structure design – LeetCode 170
Problem
Description
Design and implement a TwoSum class. It should support the following operations:add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
Example
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
Answer
Original
Code
1 | class TwoSum { |
思路
重点在于原本容纳就需要n个空间,于是索性使用unordered_map,空间复杂度$O(n)$,add操作时间复杂度$O(1)$,find操作时间复杂度$O(n)$。
Better
思路
还没看到更好的解法