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. Qt 学习之路 :Qt 线程相关类

    希望上一章有关事件循环的内容还没有把你绕晕.本章将重新回到有关线程的相关内容上面来.在前面的章节我们了解了有关QThread类的简单使用.不过,Qt 提供的有关线程的类可不那么简单,否则的话我们也没必 ...

  2. POJ2250:Compromise(LCS)

    Description In a few months the European Currency Union will become a reality. However, to join the ...

  3. Spring中的AOP

    什么是AOP? (以下内容来自百度百科) 面向切面编程(也叫面向方面编程):Aspect Oriented Programming(AOP),通过预编译方式和运行期动态代理实现程序功能的统一维护的一种 ...

  4. C++:类成员函数的重载、覆盖和隐藏区别?

    #include <iostream> class A { public: void func() { std::cout << "Hello" <& ...

  5. SpringMVC中文乱码

    刚刚构建的SpringMVC项目,一般都是中文乱码的. 这时的工程就是一个JSP页面的事情,可以添加如下代码 <%@ page language="java" import= ...

  6. MyISAM与InnoDB的区别

    1. 存储结构: MyISAM:(文件名以表名开始) .frm文件存储表定义 .MYD文件存储数据 .MYI文件存储索引 InnoDB: 所有的表保存在同一个(也可能多个)数据文件中,表的大小仅受限于 ...

  7. SpringMVC12拦截器

    创建登陆界面 <%@ page language="java" import="java.util.*" pageEncoding="utf-8 ...

  8. codevs 1994 排队 排列组合+高精度

    /* 数学题0.0 最后答案:A(n,n)*A(n+1,2)*A(n+3,m)+A(n,n)*C(m,1)*A(2,2)*C(n+1,1)*A(n+2,m-1); 简单解释一下 +之前的很显然 先排男 ...

  9. 【转】 分析iOS Crash文件:符号化iOS Crash文件的3种方法

    当你的应用提交到AppStore或者各个渠道之后,请问你多久会拿到crash文件?你如何分析crash文件的呢? 上传crash文件 你的应用应当有模块能够在应用程序crash的时候上传crash信息 ...

  10. 玩转iOS 9的UIDynamics(转)

    转自 http://www.cocoachina.com/ios/20150716/12613.html 本文由CocoaChina翻译小组成员AGSpider(微博)翻译自fancypixel的博客 ...