If you do not need to solve 2sum hashmap, but the 2sum as part of Nsum, then you need to use the pointers to solve the problem.
2sum Pseudo-code:
1. Sort the given array first
2. Walker refers to the first element, runner refers to the last element
3. When Walker is less than runner:
1) If Walker and runner are equal to target, then:
(1) If you only need a pair of solutions, record the answer, break
(2) If all solutions are required, then walker++, runner--
2) Else if and less than target,walker++
3) Else runner++
4. Return results
Time complexity of the algorithm
1. The time complexity of 2sum
The complexity of the sorting is O (Nlogn), and then the most up and down, so is O (n), so the complexity is O (N+NLOGN), so it is O (n)
2.3sum time Complexity is
Sort of time complexity O (NLOGN), in the case of each array do 2sum, but this time the 2sum does not need to sort, so this 2sum is O (N), so this part of the time complexity is O (n^2)
So the total time complexity is O (n^2+nlogn) = O (n^2)
Reference link: http://blog.csdn.net/doc_sgl/article/details/12462151#comments thank Yumbo Lord!
15.3sum (nsum Summary)