Design and implement a TwoSum class. It should support the following operations: add and find.
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.
For example,
add(1); add(3); add(5); find(4) -> true find(7) -> false
Java Solution
Since the desired class need add and get operations, HashMap is a good option for this purpose.
public class TwoSum { private HashMap<Integer, Integer> elements = new HashMap<Integer, Integer>(); public void add(int number) { if (elements.containsKey(number)) { elements.put(number, elements.get(number) + 1); } else { elements.put(number, 1); } } public boolean find(int value) { for (Integer i : elements.keySet()) { int target = value - i; if (elements.containsKey(target)) { if (i == target && elements.get(target) < 2) { continue; } return true; } } return false; } } |
put all numbers in hash.
for each number in hash, find in hash [value- number], if yes. such pair exist!
======
no need any freq table. !! it is misleading. we need put counter if in array [1 2 4 3 4 ] we are looking for 8
, so need to know exist 2 of them.
so instead of incr, if exist already, put any number not 1. thus we know it is more than 1 of 4!
elements.put(number, elements.get(number) + 1);
======
this line is confusing. no need one! just put 2 or anything not 1 . that’s all
it is done to find in [1 2 4 3 4 ] value 8.
Python3
class TwoSum:
def __init__(self):
self.values = set()
def add_me(self, num):
self.values.add(num)
def find_me(self, num):
myNum = num
seen = set()
for val in self.values:
temp = num – val
if temp in self.values:
return True
return False
A JavaScript Solution with Youtube Video Explains:
Chinese: https://www.youtube.com/watch?v=eM7GZHgclVU
Facebook: https://www.facebook.com/groups/2094071194216385/
He used hashtable as a frequency table, add will work in O(1) and find will work in O(n)
add: will check if the number already in the table, if so, increment the count by 1, else, add the number to the table.
find: will loop over the table and for each element, he will compute the (element – value), like if the value is 9 and the current element in the loop is 5, then the target should be 9 – 5 = 4, if 4 found in the table, then return true, else, check the next element and so on. If none found, return false.
can anyone explain the solution please
Unfortunately TLE, actually I tried this before and out of my luck. So I’m here to see if there’s a better solution, but still unable to find one:(
Elegant solution.