LC: 170. Two Sum III (Data structure design)
170. Two Sum III - Data structure design
Design a data structure that accepts a stream of integers and checks if it has a pair of integers that sum up to a particular value.
Implement the TwoSum class:
TwoSum()Initializes theTwoSumobject, with an empty array initially.void add(int number)Addsnumberto the data structure.boolean find(int value)Returnstrueif there exists any pair of numbers whose sum is equal tovalue, otherwise, it returnsfalse.
Example 1:
Input
["TwoSum", "add", "add", "add", "find", "find"]
[[], [1], [3], [5], [4], [7]]
Output
[null, null, null, null, true, false]
Explanation
TwoSum twoSum = new TwoSum();
twoSum.add(1); // [] --> [1]
twoSum.add(3); // [1] --> [1,3]
twoSum.add(5); // [1,3] --> [1,3,5]
twoSum.find(4); // 1 + 3 = 4, return true
twoSum.find(7); // No two integers sum up to 7, return falseConstraints:
-105 <= number <= 105-231 <= value <= 231 - 1At most
104calls will be made toaddandfind.
The Essence: Das Ziel der Frage besteht darin, den Problemlöser darüber zu informieren, wie eine Klasse zu entwerfen ist, die Queries verarbeiten kann. Es ist ebenfalls eine Variante der klassischen Frage "Two-Sum".
Details:
Hashtabellen können hierbei hilfreich sein. Man kann für alle Werte die Anwesenheit des komplementär Werts kontrollieren.
Solutions:
Default Code:
Last updated