15.3sum (nsum Summary)

Source: Internet
Author: User

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)

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.