Given an array nums of n integers and an integer target, are there elements abc, and d in nums such that a + b + cd = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [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]
]

法I:在3Sum的基础上,多加一个循环。时间复杂度O(n3)。

法II:使用HashTable。O(N^2)把所有pair存入hash表,pair中两个元素的和就是hash值。那么接下来求4sum就变成了在所有的pair value中求 2sum,这个就成了线性算法了。所以整体上这个算法是O(N^2)+O(n) = O(N^2)。

class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ret = new ArrayList<>();
Map<Integer, List<List<Integer>>> twoSum = new HashMap<>();
Map<Integer, Integer> cnt = new HashMap<>(); //count of each num //sort array
Arrays.sort(nums); for(int i = 0; i < nums.length; i++){
//update count
if(cnt.get(nums[i])==null)
cnt.put(nums[i],1);
else
cnt.put(nums[i],cnt.get(nums[i])+1); //initialize map
if(i>0 && nums[i]==nums[i-1]) continue;//avoid repeat
for(int j = i+1; j < nums.length; j++){
if(j > i+1 && nums[j]==nums[j-1]) continue; //avoid repeat List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[j]);
List<List<Integer>> listGroup = twoSum.get(nums[i]+nums[j]);
if(listGroup ==null ){
listGroup = new ArrayList<>();
}
listGroup.add(list);
twoSum.put(nums[i]+nums[j], listGroup);
}
} //iterate map to find target sum
Set<Integer> keys = twoSum.keySet();
for (int key : keys) {
List<List<Integer>> listGroupA = twoSum.get(key);
for(List<Integer> listA: listGroupA){
List<List<Integer>> listGroupB = twoSum.get(target - key);
if(listGroupB == null) continue;
for(List<Integer> listB: listGroupB){
//check whether count of num is enough
int a = listA.get(0);
int b = listA.get(1);
int c = listB.get(0);
int d = listB.get(1);
if(Math.max(a,b) > Math.min(c,d)) continue; //四个数两两组合,有6种情况,这里只取两个最小的数在listA的情况,去重 //check count of num
cnt.put(a,cnt.get(a)-1);
cnt.put(b,cnt.get(b)-1);
cnt.put(c,cnt.get(c)-1);
cnt.put(d,cnt.get(d)-1);
if(cnt.get(a) >= 0 && cnt.get(b) >= 0 && cnt.get(c) >= 0 && cnt.get(d) >= 0){
//find one list
List<Integer> listC = new ArrayList<>();
listC.addAll(listA);
listC.addAll(listB);
ret.add(listC);
} //recover count of num
cnt.put(a,cnt.get(a)+1);
cnt.put(b,cnt.get(b)+1);
cnt.put(c,cnt.get(c)+1);
cnt.put(d,cnt.get(d)+1);
}
}
}
return ret; }
}

18. 4Sum (JAVA)的更多相关文章

  1. leetcode 18 4Sum JAVA

    题目 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出 ...

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

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

  3. LeetCode 15. 3Sum 16. 3Sum Closest 18. 4Sum

    n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...

  4. 1. Two Sum&&15. 3Sum&&18. 4Sum

    题目: 1. Two Sum Given an array of integers, return indices of the two numbers such that they add up t ...

  5. leetcode 1.Two Sum 、167. Two Sum II - Input array is sorted 、15. 3Sum 、16. 3Sum Closest 、 18. 4Sum 、653. Two Sum IV - Input is a BST

    1.two sum 用hash来存储数值和对应的位置索引,通过target-当前值来获得需要的值,然后再hash中寻找 错误代码1: Input:[3,2,4]6Output:[0,0]Expecte ...

  6. Java 18套JAVA企业级大型项目实战分布式架构高并发高可用微服务电商项目实战架构

    Java 开发环境:idea https://www.jianshu.com/p/7a824fea1ce7 从无到有构建大型电商微服务架构三个阶段SpringBoot+SpringCloud+Solr ...

  7. 15. 3Sum、16. 3Sum Closest和18. 4Sum

    15 3sum Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = ...

  8. LeetCode第[18]题(Java):4Sum 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...

  9. Java [leetcode 18]4Sum

    问题描述: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d ...

随机推荐

  1. js中Array的map()函数,其中的回调函数还能这么用

    <!DOCTYPE html><html><head><meta charset="utf-8"><title>菜鸟教程 ...

  2. oracle函数操作

    感于总有些网友提出一些非常基础的问题,比如有没有实现某某功能的函数啊,某某函数是做什么用的啊,格式是什么等等,同时也感受到自己对oracle函数认识的不足,于是集中月余时间专注于oracle函数,小有 ...

  3. C#学习-图解教程(2):访问修饰符(其中两种)

    学习内容:C#:学习书籍:图解教程(中文第四版). 目录:第四章 类的基本概念 -----> 4.8 访问修饰符 访问修饰符 从类的内部,任何函数成员都可以使用成员的名称访问类中任意的其他成员. ...

  4. [纯C#实现]基于BP神经网络的中文手写识别算法

    效果展示 这不是OCR,有些人可能会觉得这东西会和OCR一样,直接进行整个字的识别就行,然而并不是. OCR是2维像素矩阵的像素数据.而手写识别不一样,手写可以把用户写字的笔画时间顺序,抽象成一个维度 ...

  5. Vue 封装可向左向右查看图片列表的组件

    <template> <div class="content-container"> <div class="content-contain ...

  6. 线上CPU100%排查

    生产服务器上部署了几个java程序,突然出现了CPU100%的异常告警,你如何定位出问题? 这个问题分为两版回答!高调版对不起,我是做研发的,这个问题在生产上是不可能遇见的!因为研发是不可能直接操作生 ...

  7. python如何安装cv2

    使用pip3 安装cv2包的时候报错 PS C:\Users\lenovo> pip3 install cv2 Collecting cv2 Could not find a version t ...

  8. Spark启动报错|java.io.FileNotFoundException: File does not exist: hdfs://hadoop101:9000/directory

    at org.apache.spark.deploy.history.FsHistoryProvider.<init>(FsHistoryProvider.scala:) at org.a ...

  9. SecureCR 控制台输出行数设置

    1.Options –>Session Options–>Terminal–>Emulation 2.在Scrollback输入你需要的最大显示行数,最大行数是128000,修改完全 ...

  10. matlab-画个拱桥和倒影?

    matlab可用于各行各业的应用中,现在我们就简单画一个拱桥试一试. r=input('请输入半径: '); z=input('请输入弧度: '); figure() %r=4; %画拱洞,用李萨如图 ...