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. [转]TopShelf 用法

    static void Main(string[] args) { { x.Service<SyncData>(s => { s.ConstructUsing(name => ...

  2. MySQL-count(*)和count(1)的查询区别

    一般情况下,Select Count (*)和Select Count(1)两着返回结果是一样的 假如表沒有主键(Primary key), 那么count(1)比count(*)快, 如果有主键的話 ...

  3. 无外接键盘安装 raspberry pi 3B+ 安装系统

    从官网介绍看,当前raspbian和以前大家的记录略有不同,老的博客资料基本都是介绍下载raspbian,但现在raspbian已经不再维护镜像, raspbian系统开始由官方 pi foundat ...

  4. shell中使用类似Python的参数处理

    params=$* for param in ${params} do name=$() value=$() if [[ "$name" = "run_type" ...

  5. 部署redis4.0-cluster

    一.部署环境 .关闭iptables(firewalld)或添加放行规则 .关闭selinux3.部署redis实例,参考:https://www.cnblogs.com/panwenbin-logs ...

  6. Flask--WTForms

    简介 WTForms是一个支持多个web框架的form组件,主要用于对用户请求数据进行验证. 安装:pip3 install wtforms 用户登录注册示例 1. 用户登录 当用户登录时候,需要对用 ...

  7. TreeMap中文排序,TreeMap倒序输出排列

    1.TreeMap集合倒序排列 import java.util.Comparator; /** * 比较算法的类,比较器 * @author Administrator * */ public cl ...

  8. intellij idea工具 DeBug调试

    断点的设定和eclipse一样,只要点一下就可以,下面是我设定的几个断点,再下面的三个窗口是用来调试代码的,这个和eclipse类似 调试常用的快捷键 F9 resume programe 恢复程序 ...

  9. Hexo+Github博客最简教程-Dockerfile自动搭建

    闲谈 拿出你的气质,打开你的电脑,借你半小时搭建好属于你的hexo博客,小生用dockerfile自动帮你搭建好:你只需要在你的mac或linux或windows上提前把docker安装好,如何安装不 ...

  10. 【Python】爬虫

    参考:http://www.cnblogs.com/fnng/p/3576154.html import urllib,re page = urllib.urlopen('http://trend.b ...