Two Sum III - Data structure design
You can design the TwoSum class using a dictionary to store the numbers and their counts. This structure will allow you to add numbers and find pairs with the desired sum efficiently.
Here’s the implementation:
- Constructor (
__init__
): Initializes the dictionary to store the numbers. add
Method: Adds the given number to the dictionary. If the number is already present, increments its count.find
Method: Iterates through the dictionary, checking if there exists a pair of numbers that sum up to the given value. Returns true if found, false otherwise.
|
|
Explanation:
add
adds the number to the dictionary and increments the count if the number is already present.find
looks for a pair that sums up to the given value. If the complement is the same as the current number, it checks if the count is greater than 1 to ensure that there are two instances of that number.
This implementation ensures that the constraints are met and provides an efficient way to add numbers and find pairs with the desired sum.