18. 4Sum (JAVA)
Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c+ d = 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)的更多相关文章
- leetcode 18 4Sum JAVA
题目 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出 ...
- [LeetCode][Python]18: 4Sum
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 18: 4Sumhttps://oj.leetcode.com/problem ...
- LeetCode 15. 3Sum 16. 3Sum Closest 18. 4Sum
n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...
- 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 ...
- 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 ...
- Java 18套JAVA企业级大型项目实战分布式架构高并发高可用微服务电商项目实战架构
Java 开发环境:idea https://www.jianshu.com/p/7a824fea1ce7 从无到有构建大型电商微服务架构三个阶段SpringBoot+SpringCloud+Solr ...
- 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 = ...
- 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 + ...
- 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 ...
随机推荐
- 学习笔记《Java多线程编程实战指南》四
JAVA线程同步机制 线程同步机制:是一套用于协调线程间的数据访问及活动的机制,该机制用于保障线程安全以及实现这些线程的共同目标.java平台提供的线程同步机制包括锁.volatile关键字.fina ...
- ubuntu16.04 install qtcreator
1. 安装相关软件,搭建环境 sudo apt install qt-creator sudo apt install qt5-default source python35/bin/activate ...
- nginx+uwsgi配置
nginx #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; ...
- dpdk环境配置
1.配置流程 [1]修改/boot/grub2/grub.cfg,添加下列标记的配置项. linux16 /vmlinuz--.el7.x86_64 root=/dev/mapper/centos-r ...
- spring事务[转]
https://www.cnblogs.com/cnmenglang/p/6410848.html 先了解事务的7种传播属性: PROPAGATION_REQUIRED -- 支持当前事务,如果当前没 ...
- DOM随时记
1.node-type 返回元素的节点类型:可以在标签上进行设置 node-type="item" ---来自新浪微博的首页写法
- 自制按钮图标的两种方法: image sprite和svg字体文件
用image sprite和svg字体文件这两种方法,都能够极大地减少小图形文件的数量, 从而减少服务器请求和带宽需求.提高网页的响应速度. 一.建立SVG字体文件 iconmoon 是一个在线工具, ...
- Python课程第五天作业
1.利用字典推导式和列表推导式完成数据的相互转化: dic = {'name': 'Owen', 'age': 18, 'gender': '男'} ls = [('name', 'Owen'), ( ...
- Java高级框架——Mybatis(二)
十.三种查询方式 1. selectList()返回值为List<resultType属性控制> 1.1 适用于查询结果都需要遍历的需求 List<Flower> list = ...
- 使用Pycharm创建Django项目
一.安装django pip install django 二.创建空django项目 选择New Project...打开创建项目向导. 成功创建一个空Django项目. 创建好的项目可以看到,已经 ...