Facebook Phone Interview: 3, 4 Sum (Easy)

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.

你可能感兴趣的:(Facebook Phone Interview: 3, 4 Sum (Easy))