Given an array S of n integers, are there elements abc, 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 be in 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)

题目大意:跟3Sum类似,这个题是在一个数组中找出4个数的和等于target,如果还用3Sum这种做法,那么复杂度会到O(N^3),效率有点不能忍。

第一种:我想到的第一种方法是枚举a+b的和,放入一个数组,然后对这个数组排序,然后以Binary Search查找target-c-d是否存在于这个数组中,这里有个问题就是排序数组还要记录a、b的下标,只能定义class或者搞个二维数组,时间复杂服是O(N^2*logN)。

To add...

第二种:后来又想到一种方法就是把枚举的a+b的和放入HashMap,以a+b之和作为key,以这两个数的下标作为value,如果分散平均的话这样的时间复杂度是O(N^2),最坏情况是所有的数都一样,那么n^2个数的和只有一个key,List里有n^2个和,退化到O(N^4)。

    public List<List<Integer>> fourSum(int[] num, int target) {
List<List<Integer>> res = new ArrayList<>();
if (num == null || num.length < 4) {
return res;
}
int len = num.length;
Map<Integer, List<Integer>> map = new HashMap<>();
Set<String> unique = new HashSet<>();
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
int key = num[i] + num[j];
if (map.get(key) == null) {
List<Integer> list = new ArrayList<>();
list.add(i * len + j);
map.put(key, list);
} else {
List<Integer> list = map.get(key);
list.add(i * len + j);
map.put(key, list);
}
}
}
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
int key = target - num[i] - num[j];
List<Integer> list = map.get(key);
if (list == null || list.isEmpty()) {
continue;
}
for (Integer pos : list) {
int x = pos / len;
int y = pos % len;
if (i == x || i == y || j == x || j == y || x == y)
continue;
int[] t = new int[]{num[i], num[j], num[x], num[y]};
Arrays.sort(t);
String uni = String.valueOf(t[0]) + t[1] + t[2] + t[3];
if (!unique.contains(uni)) {
unique.add(uni);
res.add(Arrays.asList(t[0], t[1], t[2], t[3]));
}
}
}
}
return res;
}

4Sum——LeetCode的更多相关文章

  1. 4Sum -- LeetCode

    原题链接: http://oj.leetcode.com/problems/4sum/  这道题要求跟3Sum差点儿相同,仅仅是需求扩展到四个的数字的和了.我们还是能够依照3Sum中的解法,仅仅是在外 ...

  2. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  3. Solution to LeetCode Problem Set

    Here is my collection of solutions to leetcode problems. Related code can be found in this repo: htt ...

  4. [LeetCode] 4Sum II 四数之和之二

    Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such t ...

  5. [LeetCode] 4Sum 四数之和

    Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = tar ...

  6. 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)

    转自  http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...

  7. [LeetCode][Python]18: 4Sum

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 18: 4Sumhttps://oj.leetcode.com/problem ...

  8. LeetCode之“散列表”:Two Sum && 3Sum && 3Sum Closest && 4Sum

    1. Two Sum 题目链接 题目要求: Given an array of integers, find two numbers such that they add up to a specif ...

  9. leetcode — 4sum

    import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Source : https://oj.l ...

随机推荐

  1. Android(java)学习笔记248:ContentProvider使用之虚拟短信

    1.虚拟短信应用场景:   急着脱身?应付老婆(老公.男女朋友查岗)?   使用虚拟通话短信吧.您只需通过简单设置,软件就会在指定时间会模拟一个“真实”来电或短信来迷惑对方,通过“真实”的证据让对方相 ...

  2. Linux磁盘管理:lvcreate 常用命令

    查看当前LV及PV信息: [root@rusky ~]# hostnamectl Static hostname: localhost.localdomain Transient hostname: ...

  3. php模拟HTTP协议发送post请求方法

    今天用到php模拟http发送post请求记录 代码如下: <?php $url = 'xxxx.com'; $data = 'a=one&b=two'; $data = urlenco ...

  4. noip 2012 疫情控制

    /* 考试的时候没想出正解 也没打暴力 时间不够了 随便yy了几种情况按出现的先后顺序处理而没有贪心 的了20分 不粘了 正解是围绕首都的儿子来搞的 显然先二分答案 对于每个限定的最大时间 我们尝试着 ...

  5. ASP.NET-FineUI开发实践-11

    我用实例项目写了个子父页面传值,算是比较灵活的写法,可以把js提取出来写成包,然后调用,我先一步一步写,为有困难的朋友打个样. 先画个页面: 上面是个查询用的表单,底下是表格,内存分页,用到了VBox ...

  6. json 序列化和反序列化

    Json串的格式: string strDataDiyList={"id":"1","name":"zhangsan", ...

  7. 关于Core Data的一些整理(五)

    关于Core Data的一些整理(五) 在Core Data中使用NSFetchedResultsController(以下简称VC)实现与TableView的交互,在实际中,使用VC有很多优点,其中 ...

  8. 你好,C++(8)如何表达那些始终保持不变的数据量?3.2.2 常量

    3.2.2  常量 与变量可以用在程序中表达那些可能会发生变化的数据量相对应地,在C++中,我们用常量来表达那些始终保持不变的数据量.简单来讲,就是程序中直接使用的数值.字符.字符串以及const关键 ...

  9. 【USACO 3.2.3】纺车的轮子

    [描述] 一架纺车有五个纺轮,这五个不透明的轮子边缘上都有一些缺口.这些缺口必须被迅速而准确地排列好.每个轮子都有一个起始标记(在0度),这样所有的轮子都可以在统一的已知位置开始转动.轮子按照角度变大 ...

  10. 【USACO 2.1.1】城堡

    [题目描述] 我们憨厚的USACO主人公农夫约翰(Farmer John)以无法想象的运气,在他生日那天收到了一份特别的礼物:一张“幸运爱尔兰”(一种彩票).结果这张彩票让他获得了这次比赛唯一的奖品— ...