Nine-chapter algorithm surface question 4 sum

Source: Internet
Author: User

Nine Chapters count judges Net-original website

http://www.jiuzhang.com/problem/69/

TopicsGive a bunch of arrays and a target value, and in this heap of arrays find four numbers that make their sum equal to the target value.


Online test

http://www.lintcode.com/en/problem/4-sum/

Answer

Method One:

The method of this problem is also very similar to the second solution of 2 sum. First we put the array in order first, then we still need four pointers i,j,x,y, we assume i<j<x<y, because we ordered, then A[i]<a[j]<a[x]<a[y], actually test instructions can be converted to a[ I]+a[j]+a[x]+a[y]=v. If we enumerate i,j, then test instructions can be converted to an element greater than a[j] to find a[x]+a[y] = V-a[i]-a[j], then this problem is 2sum, so we can use 2sum Two pointers point to one end of the way to solve the problem.

Method Two:

There is another way to do this problem is to use a hash table to record any of the array of two and sum = A[x]+a[y], and the record is the sum of two numbers, so that the time complexity of O (n^2) can record any two number of sum, and then in two pointers i,j (I<J) Iterate through the array and look for v-a[i]-a[j] in the hash table, and ensure that a[i],a[j],a[x],a[y] cannot take the same number, and then you can find the 4sum by i,j two-layer for loop


Nine-chapter algorithm surface question 4 sum

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.