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. About Gnu Linker1

    1 OverView ld combines a number of object and archive files, relocates their data and ties up symbol ...

  2. 01_新建WebApi后端服务项目

    1.打开微软官网: https://www.asp.net/learn 2.查看文章: https://docs.microsoft.com/en-us/aspnet/web-api/overview ...

  3. 盒子尺寸父子传递及嵌套Demo

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. for update 与where current of的问题

    在刚学oracle时一直不明白for update 的作用,今天考试又遇到郁闷半天,所以加以整理. 一: 1>首先for update是对表的行进行锁定.锁定就好比我们学java Thread那 ...

  5. Kettle通过Webservice获取天气信息

      Kettle通过Webservice获取天气信息 需求: 通过kettle工具,通过webservice获取天气信息,写成xml格式文件. 思路: Kettle可通过两种选择获取webservic ...

  6. 【转载】Google 程序员消灭 Bug 的 5 大法宝!

    遇到问题怎么办?还能怎么办,解决呗.那到底怎么解决呢?你是有什么惯用的逻辑模式.解决策略,还是全靠直觉手感? 本文中,一位 Google 程序员将“现场”演示其解决编程问题的始末,看看有套路的问题解决 ...

  7. 装python package 时,conda提示会升级python2到python3,那可能是你的windows不支持py2env下的此包。

    装python package 时,conda提示会升级python2到python3, 那可能是你的windows不支持py2env下的此包.比如:win 下,tensorflow就不支持py2的环 ...

  8. Centos7.3 编译安装GDAL以及Python的GDAL包

    参考: https://cryolite.iteye.com/blog/176382 https://blog.csdn.net/a13326021319/article/details/782505 ...

  9. gp工具的许可

    还是要在代码里许可 static class Program { [STAThread] static void Main() { ESRI.ArcGIS.RuntimeManager.Bind(ES ...

  10. 在虚拟机上的ubuntu 1.6 系统中sudo apt-get失败的问题

    在虚拟机上sudo apt-get update 失败.可能是网络dns问题,把nameserver \设为你路由器的内网ip地址就没事了; 详细: 1/打开sudo gedit /etc/resol ...