Summation Problem Summary (Leetcode 2Sum, 3Sum, 4Sum, K sum)

Source: Internet
Author: User
Tags constant hash

Http://tech-wonderland.net/blog/summary-of-ksum-problems.html

Preface:

People who have done leetcode know that there are 2sum, 3sum (closest), 4sum and other issues, these are also the interview of the classic questions, to investigate whether it can be reasonable to use the nature of sorting, step by step to get efficient algorithm. After summing up, I think these problems can be summed up with a general sum of K sum problem to digest, here we first directly give the K sum problem description and algorithm (recursive solution), and then apply this general method to the specific k, such as Leetcode 2Sum, 3Sum, 4Sum problem. At the same time, we also give a discussion of another hashing algorithm. Leetcode Summation problem description (K sum problem):

The sum of K sums is generally described in this way: give you a set of n numbers (such as vector<int> num), and then give you a constant (for example, int target), our goal is to find K numbers in this heap number, Make the sum of the k numbers equal to target. Precautions (constraints):

Note that this set of numbers may have duplicates: for example, 1 1 2 3, 3sum, then target = 6, you may get two sets of 1 2 3, 1 2 3,1 from the first 1 or the second 1, but the result is actually only one group, so the final result is going to be heavy. K sum solution for Leetcode 2Sum, 3Sum, 4Sum:

Method One: Violence, is to enumerate all the k-subset, then this complexity is to choose K from N, the complexity is O (n^k)

Method Two: Sort, this algorithm can consider the simplest case, 2sum, this is a classic problem, the method is to sort first, and then use the tail pointer to find two numbers so that their and equal to target, this 2sum algorithm on-line search has, here do not repeat, give 2sum core code:

2 sum
int i = starting;//head pointer
int j = num.size ()-1;//tail pointer while
(i < j) {
    int sum = num[i] + num[j];
    if (sum = = target) {
        store num[i] and num[j] somewhere;
        If (we need only one such pair of numbers) break
            ;
        Otherwise do
            ++i,--j;
    }
    else if (sum < target)
        ++i;
    else
        --j;
}

2sum algorithm complexity is O (n log n) because the sorting with n log n and the tail pointer of the search is linear, so the overall is O (n log n), OK now consider 3sum, with 2sum actually 3sum is not difficult, so think: First Take out a number, So I just have to find two numbers in the remaining numbers to make them equal to (target– the number taken out). So 3sum degenerate into 2sum, take out a number, so the number has N, so the algorithm complexity of 3sum is O (n^2), note here the complexity is N squared, because you sort only need to row, the back of the work is to take out a number, and then find the remaining two numbers, Looking for two numbers is 2sum with the tail-pointer linear sweep, it is easy to mistakenly calculate the complexity of O (n^2 log N), this is not right. We continue to the words 4sum can degenerate into a 3sum problem, then and so on, k-sum step by step degradation, the last is to solve a 2sum problem, K sum of the complexity is O (n^ (K-1)). This field seems to be the best of the world, that is, k-sum problem is the best can be done O (n^ (K-1)) complexity, have seen some people said can be strictly mathematical proof, here is not in-depth study. K Sum (2Sum, 3Sum, 4Sum) algorithm optimization (optimization):

Here two points, first, note, such as 3sum, the first order of the whole, and then enumerate the third number when the time does not need to repeat, such as the number after the order is a B c D E F, then the first enumeration A, in the remaining B C D E F 2 sum, after the second enumeration B, only need to C d E F 2sum OK, rather than in a C D E F 2sum, this people can feel it, figured out or very helpful. Second, K sum can write a recursive program very elegant solution, specific people can try it yourself. When writing recursion, be careful not to repeat the order. Hash Solution (Other):

In fact, such as 2sum or linear solution, is to use HashMap, so that you check a value exists is a constant time, then given a sum, as long as the linear scan, for each number judge Sum–num existence does not exist. Note that this algorithm is also applicable for sequences with duplicate elements. For example 2 3 3 4 then Hashtable can make hash (2) = 1; Hash (3) = 1, hash (4) =1 others are 0, then check, sweep to two times 3 are check sum–3 in the Hashtable, note that the final return to all the matching pair is also going to heavy. This kind of promotion 3sum actually also has O (n^2) Similar hash algorithm, this and previously did not improve, but 4sum will have a faster algorithm. 4sum hash Algorithm:

O (n^2) put all the pair into the hash table, and each hash value below can be made map with a list, map[hashvalue] = list, each list element is a pair, this pair and is the hash value, Then the next 4sum becomes in all the pair value of 2sum, this becomes a linear algorithm, note that the linearity here is also for the pair number (n^2) linear, so the overall algorithm is O (n^2), and because we hang up the list, So as long as we meet 4sum, we can find out which four numbers correspond to each other.
On the solution of hash I am not a lot of research, later if there is more in-depth research and update. Concluding remarks:

This article mainly from the general K sum problem point of view summarizes those more classical summation problems such as leetcode inside the 2sum, 3sum (closest), 4sum and other issues, the article first directly gives the k sum of the problem description and algorithm (recursive solution), This general method is then applied to the specific k, such as 2Sum, 3Sum, 4Sum problems in Leetcode. We also give a discussion of another hashing algorithm. Then this article basically still think of what to write, there is negligence wrong place please correct, also welcome message discussion, if you need source code, please leave a message or email to info@tech-wonderland.net

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.