题目:
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
思路:
需要考虑的一个特殊情况是:数组中有可能有重复元素,即如果需要查找的值为8,那么可能由4+4构成,这样如果只有一个4是无法构成8的,因此还需要同时考虑每个数组元素出现的次数。在解决的过程中,我们可以根据add优先还是find优先,确定不同的存储结构。
1、add优先:在这种策略中,我们假定add调用的次数要远远多于find调用的次数。所以设计add函数的时间复杂度为O(1),find函数的时间复杂度为O(n)。此时我们哈希nums的值。
2、find优先:在这种策略中,我们假定find调用的次数要远远多于add调用的次数。所以我们设计add函数的时间复杂度是O(n),find函数的时间复杂度是O(1)。此时哈希的是sums的值。需要注意的是,我写的这段代码没有通过所有的测试用例(因为里面的add操作太多了),但是这确实提供了一种在软件设计中trade-off的思考方式。我想如果在面试的过程中能够给面试官展示你这方面的思考和能力,是会有加分的。
代码:
1、add优先:
class TwoSum {
public:
/** Initialize your data structure here. */
TwoSum() {
}
/** Add the number to an internal data structure.. */
void add(int number) {
++hash[number];
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
bool find(int value) {
for (auto val : hash) {
if (value != 2 * val.first && hash.count(value - val.first)) {
return true;
}
if (value == 2 * val.first && val.second > 1) {
return true;
}
}
return false;
}
private:
unordered_map<int, int> hash;
};
/**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* bool param_2 = obj.find(value);
*/
2、find优先:
class TwoSum {
public:
/** Initialize your data structure here. */
TwoSum() {
}
/** Add the number to an internal data structure.. */
void add(int number) {
for (int i = 0; i < nums.size(); ++i) {
sums.insert(nums[i] + number);
}
nums.push_back(number);
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
bool find(int value) {
return sums.find(value) != sums.end();
}
private:
vector<int> nums;
unordered_set<int> sums;
};
/**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* bool param_2 = obj.find(value);
*/