Leetcode: 4sum_leetcode

Source: Internet
Author: User

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)

Four number of added and target numbers in a given array

The way to solve problems: double pointers, same as 3Sum

Code:

public class Solution {public list<list<integer>> foursum (int[] nums, int target) {list<list&
        lt;integer>> result = new arraylist<list<integer>> ();

        Arrays.sort (Nums); for (int i = 0; i < nums.length-3 i++) {if (i > 0 && nums[i] = = Nums[i-1]) {C
            Ontinue; for (int j = i + 1; j < Nums.length-2; J + +) {if (J > i + 1 && nums[j] = = Nums [J-1])
                {continue;
                int k = j + 1;

                int L = nums.length-1;
                        while (K < L) {if (K > J + 1 && nums[k] = = Nums[k-1]) {k++;
                    Continue
                        } if (L < nums.length-1 && nums[l] = = nums[l + 1]) {l--;
                    Continue

              }      int sum = Nums[i] + nums[j] + nums[k] + nums[l];
                        if (sum = = target) {list<integer> temp = new arraylist<integer> ();
                        Temp.add (Nums[i]);
                        Temp.add (Nums[j]);
                        Temp.add (Nums[k]);
                        Temp.add (Nums[l]);
                        Result.add (temp);
                        k++;
                    l--;
                    }else if (sum < target) {k++;
                    }else{l--;
    }}} return result; }
}

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.