Two Sum III - Data structure design

Design and implement a TwoSum class. It should support the following operations:addandfind.

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 1:

add(1); add(3); add(5);
find(4) -> true
find(7) -> false

Example 2:

add(3); add(1); add(2);
find(3) -> true
find(6) -> false

Analysis

Trade Off:

Add vs Find

Approach 1:

using two hashset to store unique number and unique sum when add(), add to unique sum and num, this will have O(n) time for add(), and O(1) for find(). The space complexity though is O(n^2), which unique set for sum will consume O(n^2) space.

Approach 2:

One hashmap for unique numbers, and their count (to tackle multiple duplicate numbers issue)

If it's more add() intensive, then using O(1) time for add(), and O(n) time for find();

if it's more find() intensive, then use O(n) time for add(), and O(1) for find().

Seems that LeetCode's test case tends to have much more add() operations, and approach 1 will have TLE, thus approach 2 is preferred in that case.

几点思考:

  1. List的iterator比HashMap的iterator

Solution

Approach 2 - HashMap - Time Complexity: O(n) find, O(1) add, Space Complexity: O(n)

Optimized with lower & upper limit

Add low + low2 < value < high + high2 boundary to further reduce the runtime.

Approach 1 - TLE

Last updated

Was this helpful?