Java [Leetcode 18]4sum

Source: Internet
Author: User

Problem Description:

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)

Problem Solving Ideas:

Similar to the previous 3sum, except that there is a set of loops outside, with a time complexity of O (n^3)

The code is as follows:

public class Solution {list<list<integer>> ans = new arraylist<list<integer>> ();p ublic List&lt ; List<integer>> foursum (int[] nums, int target) {int length = Nums.length;int tmp;if (nums = NULL | | Length < 4) return ans; Arrays.sort (Nums); for (int i = 0; i < length-3, i++) {if (i > 0 && nums[i] = = Nums[i-1]) continue;for (in T j = i + 1; J < Length-2;  J + +) {if (J > i + 1 && nums[j] = = nums[j-1]) Continue;int begin = j + 1;int end = Length-1;while (Begin < End) {tmp = Nums[begin] + nums[end] + nums[i] + nums[j];if (tmp = = target) {list<integer> List = new Arraylist<i Nteger> (); List.add (Nums[i]); List.add (Nums[j]); List.add (Nums[begin]); List.add (Nums[end]); Ans.add (list); while (Begin < End && Nums[begin + 1] = = Nums[begin]) begin++;begin++;while (Begin < End && Nums[end-1] = = Nums[end]) end--;end--;} else if (tmp > Target) end--;elsebegin++;}}} return ans;}}

Java [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.