450. Two Sum III – Data Structure Design
Design a data structure that allows adding numbers to a collection and efficiently checks whether any two numbers in the collection sum to a given target.
Implement the TwoSum class:
- TwoSum(): Initializes an empty data structure.
- void add(int number): Inserts number into the collection.
- boolean find(int value): Returns true if there exist two distinct numbers in the collection whose sum equals value, otherwise returns false.
Example 1:
Input: ["TwoSum()", "add(2)", "add(6)", "add(8)", "find(10)", "find(12)"]
Output: [null, null, null, null, true, false]
Explanation:
- TwoSum twoSum = new TwoSum();
- twoSum.add(2); // [] → [2]
- twoSum.add(6); // [2] → [2,6]
- twoSum.add(8); // [2,6] → [2,6,8]
- twoSum.find(10); // 2 + 8 = 10, return true
- twoSum.find(12); // No two numbers sum up to 12, return false
Example 2:
Input: ["TwoSum()", "add(-1)", "add(0)", "add(1)", "add(3)", "find(2)", "find(4)"]
Output: [null, null, null, null, null, true, false]
Explanation:
- TwoSum twoSum = new TwoSum();
- twoSum.add(-1); // [] → [-1]
- twoSum.add(0); // [-1] → [-1,0]
- twoSum.add(1); // [-1,0] → [-1,0,1]
- twoSum.add(3); // [-1,0,1] → [-1,0,1,3]
- twoSum.find(2); // -1 + 3 = 2, return true
- twoSum.find(4); // No two numbers sum up to 4, return false
Now Your Turn!
Pick the correct output for the given inputInput: ["TwoSum()", "add(4)", "add(7)", "add(11)", "add(15)", "find(18)", "find(20)"]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- −105 ≤ number ≤ 105
- −231 ≤ value ≤ 231−1
- At most 104 calls will be made to add and find