LeetCode 170: Two Sum III - Data structure design
LeetCode 170 Solution Explanation
Explanation:
To design a data structure that supports two operations:
add(num)
: Add the numbernum
to the data structure.find(target)
: Find if there exist two numbers such that their sum is equal totarget
.
We can use a hashmap to store the numbers and their frequencies. When adding a number, we store it in the hashmap along with its frequency. When finding a pair that sums up to the target, we iterate through the hashmap and check if target - num
exists in the hashmap.
LeetCode 170 Solutions in Java, C++, Python
import java.util.HashMap;
class TwoSum {
private HashMap<Integer, Integer> map;
public TwoSum() {
map = new HashMap<>();
}
public void add(int num) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
public boolean find(int target) {
for (int num : map.keySet()) {
int complement = target - num;
if ((num == complement && map.get(num) > 1) || (num != complement && map.containsKey(complement))) {
return true;
}
}
return false;
}
}
Interactive Code Editor for LeetCode 170
Improve Your LeetCode 170 Solution
Use the editor below to refine the provided solution for LeetCode 170. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...