"018-4sum (four-digit and)" " leetcode-interview algorithm classic-java Implementation" "All topic Directory Index" Original title
Given an array s of n integers, are there elements a, B, C, and D in s such that A + B + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must being in the non-descending order. (ie, a≤b≤c≤d)
The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0-1 0-2 2}, and target = 0.
A solution set is:
( -1, 0, 0, 1)
( -2,-1, 1, 2)
( -2, 0, 0, 2)
The main effect of the topic
Given an array of integers, find the unique solution of A + B + c + d = target.
ideas for solving problems
The
First determines the two number of a and d, and cannot be reused for both A and d two numbers. Then determine B and C, and the same two numbers cannot be reused at the same time. Find all the solutions that satisfy the conditions, while ensuring that the solutions are not duplicated.
Code implementation
Import java.util.ArrayList;
Import Java.util.Arrays;
Import java.util.LinkedList;
Import java.util.List; public class Solution {public list<list<integer>> foursum (int[] num, int target) {LIST<LIST&L
t;integer>> result = new linkedlist<> ();
if (num = null | | Num.length < 4) {return result; } arrays.sort (num); Array to sort for (int i = 0; i < num.length-3 i++) {//First addends if (i > 0 && num[i] = =
Num[i-1]) {//The first addends uses a continue that does not repeat; for (int j = Num.length-1 J > i + 2; j--) {//Fourth addends if (J < Num.length-1 &
& Num[j] = = num[j + 1]) {//Fourth addends use not duplicate continue; int start = i + 1; The second addends int end = J-1;
Third addends int n = target-num[i]-num[j]; while (Start < end) {if (NuM[start] + num[end] = = N) {list<integer> four = new arraylist<> (4);
Four.add (Num[i]);
Four.add (Num[start]);
Four.add (Num[end]);
Four.add (Num[j]);
Result.add (four);
do {start++; while (start< end && Num[start] = = num[start-1]);
Guaranteed to use the second number again does not repeat do {end--; while (Start < end && Num[end] = = num[end + 1]);
Make sure to use the third number again not repeat} else if (Num[start] + num[end] < N) {do {
start++; while (start< end && Num[start] = = num[start-1]);
Make sure to use the second number again without repeating} else {do {end--; while (Start < end && Num[end] = = num[end + 1]);
Ensure that the third number is not repeated}}} return result;
}
}Evaluation Results
Click on the picture, the mouse does not release, drag a position, released in a new window to view the full picture.
Special Notes Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/46997233"