[Leetcode 18]4sum

Source: Internet
Author: User

1 Topics:

Given an array S of n integers, is 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 is in non-descending order. (ie, abcd)
    • 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)

2 Ideas

First, you have to understand 3Sum.

Then follow the idea of 3Sum, it is good to do. The main one is to traverse all four combinations. The sort is sure. See the code for details and think for yourself. Time complexity O (n^3) did a few questions, feeling a bit of a state.

3 Code

     PublicList<list<integer>> Foursum (int[] Nums,inttarget) {List<List<Integer>> result =NewArraylist<list<integer>>(); intLen =nums.length; if(Len < 4){            returnresult;        } arrays.sort (Nums); intHead = 0; intEnd = Len-1;  while(Head < End-2){             while(Head < End-2){                intPre = head + 1; intsuffix = end-1; /*Compare all four group between pre & Suffic*/                 while(Pre <suffix) {                    intsum = nums[head]+nums[end]+nums[pre]+Nums[suffix]; if(Sum <target) {                        ++Pre; }Else if(Sum >target) {                        --suffix; }Else{result.add (Arrays.aslist (Nums[head],nums[pre],nums[suffix],nums[end])); ++Pre; --suffix;  while(Pre <= suffix && nums[pre]==nums[pre-1]) + +Pre;  while(Pre <= suffix && nums[suffix]==nums[suffix+1])--suffix; }                }                /*for each nums[head], Compore all Nums[head] until head<end-2*/++Head;  while(Head<end-2 && nums[head]==nums[head-1]) + +Head; }            /*set head to 0 & End-1, so we can traverse all four groups*/Head=0; --end;  while(head<end-2 &&nums[end] = = nums[end+1])--end; }            returnresult; }

[Leetcode 18]4sum

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.