題目
這個(gè)數(shù)據(jù)結(jié)構(gòu)主要是把數(shù)據(jù)存儲(chǔ)到unordered_multiset里,multiset類似set翰舌,但是它允許重復(fù)元素的存在盅安。
這是cplusplus.com里關(guān)于unordered_multiset的指引
unordered_multiset reference
實(shí)現(xiàn)find函數(shù)我原本的思路是用set.find(n - value), 但是發(fā)現(xiàn)這個(gè)方法不能解決例如 set: {0}, find(0) 這樣的情況唤锉,所以我選擇了是用multiset的count函數(shù),如果value == value - n别瞭, 那在multisite中至少要這個(gè)value出現(xiàn)兩次才能滿足 n + (value - n) == value 此處n 與 value - n 是值相同的不同元素
class TwoSum {
public:
// Add the number to an internal data structure.
void add(int number) {
nums.insert(number);
}
// Find if there exists any pair of numbers which sum is equal to the value.
bool find(int value) {
for (auto n: nums) {
?? int count = value - n == n ? 2 : 1;
if (nums.count(value - n) >= count) return true;
}
return false;
}
private:
unordered_multisetnums;
};