Facebook really usually has a high frequency of posting repetitive problems.
This one is the typical 3Sum, 4Sum problem.
Given an input array and a target value, find whether there are three/four values in the array which sum to the target. target value can be 0.
The input array may contains repetitive numbers.
// Typical problems.
// find 3 values in the input array which sum to the target. If not exist, return NULL.
vector< vector<int> > findThreeSum(vector<int> array, int target) {
vector< vector<int> > res;
if(array.size() < 3) return res; // if the input array has less than 3 values, just return empty vector.
sort(array.begin(), array.end()); // need to sort this array first to avoid repeat combinations.
for(int i = 0; i < array.size(); ++i) {
if(i > 0 && array[i] == array[i-1]) continue; // if array[i] == array[i+1], skip the (i+1)th number.
int start = i + 1;
int end = array.size() - 1;
while(start < end) {
if(start - 1 > i && (array[start] == array[start + 1])) {
start++;
continue; // kick out the repetitive values.
}
if(end + 1 < array.size() && (array[end] == array[end + 1])) {
end--;
continue; // same here.
}
int sum = array[i] + array[start] + array[end];
if(sum == target) {
vector<int> back;
back.push_back(array[i]);
back.push_back(array[start]);
back.push_back(array[end]);
res.push_back(res);
} else if(sum < target) {
start++;
} else end--;
}
}
return res;
}
Sort algorithm takes o(NlgN), Final Time Complexity is O(n^2)
To be continue: this problem can use HashTable to solve as well.
Two Sum, solve it using hashtable
#include <vector>
#include <iostream>
#include <set>
using namespace std;
bool twoSum(vector<int>& nums, int target) {
set<int> maps;
for(int i = 0; i < nums.size(); ++i) {
if(maps.find(target - nums[i]) == maps.end()) {
maps.insert(nums[i]);
} else return true;
}
return false;
}
int main(void) {
vector<int> nums {0, 1, 2};
cout << twoSum(nums, 1) << endl;
}
However, the hash table one will be problematic once the input number are float.
Because hash table is used for fast loopup for exact numbers and most floats are the result of caculations that produce a float which is only an approximation to the correct number. Normally, because of rounding and inherent limitations of floating point arithmetic, if you expect that floating point number a and b should be equal to each other because math says so, you need to pick some relatively small delta > 0...