该题用Array或HashTable都可以。
Array: add()时间复杂度O(n),find()时间复杂度O(n)。
HashTable: add()时间复杂度O(1), find()时间复杂度O(n)。
解法1:Array。add()用类似插入排序。find()用双指针。
代码:
class TwoSum {
public:
/*
* @param number: An integer
* @return: nothing
*/
void add(int number) {
nums.push_back(number);
int i=0, pos=0;
int len=nums.size();
//similar to insertion sort
for (i=0; i<len-1; ++i) {
if (number<=nums[i]) {
break;
}
}
pos=i;
for (i=len-1; i>pos; --i) {
nums[i]=nums[i-1];
}
nums[pos]=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) {
int p1=0, p2=nums.size()-1;
while(p1<p2) {
int sum=nums[p1]+nums[p2];
if (sum==value) {
return true;
} else if (sum>value) {
p2--;
} else {
p1++;
}
}
return false;
}
private:
vector<int> nums;
};
解法2: HashTable。
代码如下:
class TwoSum {
public:
void add(int number) {
unordered_multimap<int, int>::iterator it = dict.find(number);
if (it == dict.end()) {
dict.insert(pair<int, int>(number, 1));
} else {
it->second++;
}
}
bool find(int value) {
for (auto h : dict) { //or unordered_multimap<int,int>::iterator it; for (it=dict.begin(); it!=m.end(); it++)
auto it=dict.find(value-h.first); //note: h is not pointer, it is a pointer!!!
if (it != dict.end()) {
if ((value==(it->first << 1)) && (it->second==1)) continue; //8=4+4 but there is only one 4, then continue. Note: not return false here!
return true;
}
}
return false;
}
private:
unordered_multimap<int, int> dict;
};