您的位置:首页 > 其它

Two Sum - Data structure design

2017-10-19 14:51 288 查看
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.

java

public class TwoSum {
/*
* Add the number to an internal data structure.
* @param number: An integer
* @return: nothing
*/
Map<Integer, Integer> map = null;
List<Integer> list = null;
public TwoSum() {
map = new HashMap<>();
list = new ArrayList<>();
}
public void add(int number) {
// write your code here
if (map.containsKey(number)) {
map.put(number, map.get(number) + 1);
} else {
map.put(number, 1);
list.add(number);
}
}
/*
* @param value: An integer
* @return: Find if there exists any pair of numbers which sum is equal to the value.
*/
public boolean find(int value) {
// write your code here
for (int i = 0; i < list.size(); i++) {
int num = list.get(i);
int target = value - num;
if (num == target && map.get(num) > 1) {
return true;
} else if (num != target && map.containsKey(target)) {
return true;
} else {
continue;
}
}
return false;
}
}

// Your TwoSum object will be instantiated and called as such:
// TwoSum twoSum = new TwoSum();
// twoSum.add(number);
// twoSum.find(value);

python

class TwoSum:
"""
Add the number to an internal data structure.
@param: number: An integer
@return: nothing
"""
def __init__(self):
self.mapping = {}

def add(self, number):
# write your code here
if number in self.mapping:
self.mapping[number] += 1
else:
self.mapping[number] = 1

"""
@param: value: An integer
@return: Find if there exists any pair of numbers which sum is equal to the value.
"""
def find(self, value):
# write your code here
for ele in self.mapping:
target = value - ele
if target == ele and self.mapping[ele] > 1:
return True
elif target != ele and target in self.mapping:
return True
else:
continue
return False

# Your TwoSum object will be instantiated and called as such:
# twoSum = TwoSum()
# twoSum.add(number)
# twoSum.find(value)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: