2018-04-16
2018-04-16 本文已影响0人
aammyytt
題目:
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.
思路:
代碼:
class TwoSum {
public:
/*
* @param number: An integer
* @return: nothing
*/
multiset<int> nums;
void add(int number) {
// write your code here
nums.insert(number);
}
/*
* @param value: An integer
* @return: Find if there exists any pair of numbers which sum is equal to the value.
*/
bool find(int value) {
// write your code here
for (int i : nums) {
int need_count;
if (i == value-i)
need_count = 2;
else
need_count = 1;
//如果在裡面找到配對的
if (nums.count(value - i) >= need_count) {
return true;
}
}
return false;
}
};