描述

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: The solution set must not contain duplicate quadruplets.

示例

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]
]

算法分析

难度:中

分析:给定整型数组和指定一个整型目标值,从整形数组中找出4个不同的元素,使得4个元素之和等于目标值,返回结果为所有满足上述条件的元素组合。

思路:思路可以参考3Sum,主要难度是由原先的找3个元素之和,变成了找4个元素之和。这种情况下,其实有点像解魔方:玩五阶魔方就是从五阶降到四阶,然后再从四阶降到三阶,最后再按照玩三阶魔方的方法解决问题。

最终的解法,其实就是在3阶解法的基础上,在外层再套一层4阶的循环,并做一些基础的判断,复杂度也是在3阶n²基础上*n=n³,当然,这种算法也可推广到n阶。

代码示例(C#)

public IList<IList<int>> FourSum(int[] nums, int target)
{
List<IList<int>> res = new List<IList<int>>();
if (nums.Length < 4) return res; //排序
Array.Sort(nums);
//4阶判断
for (int i = 0; i < nums.Length - 3; i++)
{
//如果最近4个元素之和都大于目标值,因为数组是排序的,后续只可能更大,所以跳出循环
if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break;
//当前元素和最后3个元素之和小于目标值即本轮最大值都小于目标值,则本轮不满足条件,跳过本轮
if (nums[i] + nums[nums.Length - 1] + nums[nums.Length - 2] + nums[nums.Length - 3] < target)
continue;
//防止重复组合
if (i > 0 && nums[i] == nums[i - 1]) continue; //3阶判断
for (int j = i + 1; j < nums.Length - 2; j++)
{
//原理同4阶判断
if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) break;
if (nums[i] + nums[j] + nums[nums.Length - 1] + nums[nums.Length - 2] < target)
continue; int lo = j + 1, hi = nums.Length - 1;
while (lo < hi)
{
//已知元素 nums[i],nums[j],剩下2个元素做夹逼
int sum = nums[i] + nums[j] + nums[lo] + nums[hi];
if (sum == target)
{
res.Add(new List<int> { nums[i], nums[j], nums[lo], nums[hi] });
while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
lo++;
hi--;
}
//两边夹逼
else if (sum < target) lo++;
else hi--;
}
}
}
return res;
}

复杂度

  • 时间复杂度O (n³).
  • 空间复杂度O (1).

附录

算法题丨4Sum的更多相关文章

  1. 算法题丨Two Sum

    描述 Given an array of integers, return indices of the two numbers such that they add up to a specific ...

  2. 算法题丨3Sum

    描述 Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all ...

  3. 算法题丨3Sum Closest

    描述 Given an array S of n integers, find three integers in S such that the sum is closest to a given ...

  4. 算法题丨Remove Duplicates from Sorted Array II

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? 示例 Giv ...

  5. 算法题丨Longest Consecutive Sequence

    描述 Given an unsorted array of integers, find the length of the longest consecutive elements sequence ...

  6. 算法题丨Remove Element

    描述 Given an array and a value, remove all instances of that value in-place and return the new length ...

  7. 算法题丨Move Zeroes

    描述 Given an array nums, write a function to move all 0's to the end of it while maintaining the rela ...

  8. 算法题丨Next Permutation

    描述 Implement next permutation, which rearranges numbers into the lexicographically next greater perm ...

  9. 算法题丨Remove Duplicates from Sorted Array

    描述 Given a sorted array, remove the duplicates in-place such that each element appear only once and ...

随机推荐

  1. Android学习之AutoCompleteTextView和MultiAutoCompleteTextView

    转自:http://blog.csdn.net/qq_28468727/article/details/52258409 AutoCompleteTextView.MultiAutoCompleteT ...

  2. flask项目部署到阿里云 ubuntu16.04

    title: flask项目部署到阿里云 ubuntu16.04 date: 2018.3.6 项目地址: 我的博客 部署思路参考: Flask Web开发>的个人部署版本,包含学习笔记. 开始 ...

  3. JavaScript之事件及动画

    一.事件 常用事件 click(function(){...}) //单击事件 hover(function(){...}) //鼠标经过事件 blur(function(){...}) //失去光标 ...

  4. java语言与jvm虚拟机简介

    一.java语言 1.1 支持面向对象编程oop 强调支持,因为java同样可以面向过程编程. oop的三大特性是:封装.继承.多态. 封装主要针对成员变量而言,oop的思想要求成员变量均为私有,不应 ...

  5. webpack使用教程

    webpack使用教程 接触webpack也有挺长一段时间了,公司的项目也是一直用着webpack在打包处理,但前几天在教新人的情况下,遇到了一个问题,那就是:尽管网上的webpack教程满天飞,但是 ...

  6. springMVC的异常处理

    1. 异常 什么是异常: 在程序中预期会出现,但是却无法处理的问题,叫做异常 异常处理原则: 延迟处理 先记着...,后续补充

  7. 笔记:创建Jersey REST 服务,基于Maven

    基于Java SE 形式的REST服务 创建项目 我们首选使用 archetypeGroupId 为 org.glassfish.jersey.archetypes 的原型,archetypeArti ...

  8. Matlab绘图基础——散点生成三角网(TIN)

    %例一:二维三角网TIN模型的生成 X=rand(10,2)*5; dt=DelaunayTri(X(:,1),X(:,2));       %生成三角网 triplot(dt);hold on;   ...

  9. RedHat/Fedora/Centos 下bash 自动补全命令

    本文转自:运维生存时间:http://www.ttlsa.com/linux/rhel- ... matically-function/ linuser  :http://www.linuser.co ...

  10. C#,DataHelper,一个通用的帮助类,留个备份。

    using System; using Newtonsoft.Json; using System.IO; using System.Text; namespace CarHailing.Base { ...