当前位置:网站首页>[leetcode] 18. Sum of four numbers
[leetcode] 18. Sum of four numbers
2022-07-06 05:09:00 【Xiaoqu classmate】
subject :
Here you are n An array of integers nums
, And a target value target
. Please find and return the quads that meet all the following conditions and are not repeated [nums[a], nums[b], nums[c], nums[d]]
( If two Quad elements correspond to each other , It is considered that two quads repeat ):
0 <= a, b, c, d < n
a、b、c and d Different from each other
nums[a] + nums[b] + nums[c] + nums[d] == target
You can press In any order Return to the answer .
Example 1:
Input :nums = [1,0,-1,0,-2,2], target = 0
Output :[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:
Input :nums = [2,2,2,2,2], target = 8
Output :[[2,2,2,2]]
Tips :
1 <= nums.length <= 200
-10^9 <= nums[i] <= 10 ^9
-10^9 <= target <= 10 ^9
Their thinking :
I believe you have done the sum of three numbers before , So the idea of this topic , You can refer to the sum of three numbers , Use double pointer .
You can refer to it Sum of three numbers Make a comparison , What are the similarities and differences .
Because we need to use double pointers , So sorting is a must .
There is also the sum of three numbers , Sum of four numbers ...n Sum of numbers and so on , It's the same thing , This time I'll write you a n Sum of the numbers , You can recite it directly , I'll never be afraid again n The sum of the numbers .
Specific code :
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
if (nums.length < 4) {
return new LinkedList<>();
}
return nSum(nums, target, 4, 0);
}
// Recursive parameters :nums, Current target value target, Number of current values n, The starting index of the current value start
// return n A list of numbers and , namely n Tuples
List<List<Integer>> nSum(int[] nums, long target, int n, int start) {
// Every layer of recursion should be created res To pass the list
List<List<Integer>> res = new ArrayList<>();
// The termination layer of recursion :2 Sum of the numbers
if (n == 2) {
int left = start, right = nums.length - 1;
while (left < right) {
// prune : Select the closed interval according to the rest [left, right] Prune the minimum and maximum values in
// If from the current left,left+1 The minimum value ratio of composition target Big words , The rest left and right It's even bigger
// So jump out , Traverse i+1
int nMin = nums[left] + nums[left + 1];
if (nMin > target) {
break;
}
// And nMin Empathy
int nMax = nums[right] + nums[right - 1];
if (nMax < target) {
break;
}
long sum = nums[left] + nums[right];
if (sum == target) {
List<Integer> row = new LinkedList<>();
row.add(nums[left]);
row.add(nums[right]);
res.add(row);
// duplicate removal 2: Remove the repetition of the last two values
while (left < right && nums[left] == nums[++left]) ;
while (left < right && nums[right] == nums[--right]) ;
} else if (sum < target) {
while (left < right && nums[left] == nums[++left]) ;
} else {
while (left < right && nums[right] == nums[--right]) ;
}
}
}
// Normal recursion layer :
else {
for (int i = start; i <= nums.length - n; i++) {
// duplicate removal 1: Remove the repetition of the current value . Comparison between current value and historical value ,i-1 Executed
// Be careful , If de duplication is placed in front of the code block , Just use if continue as well as i-1 and i In the form of ,
// If put in the back , Namely while i++ as well as i and i+1 In the form of
if (i > start && nums[i - 1] == nums[i]) {
continue;
}
// sub Catch the result of recursion
List<List<Integer>> sub = nSum(nums, target - nums[i], n - 1, i + 1);
// // After the sequence returns, the operation on the current layer :res add to sub And the current value
for (List<Integer> row : sub) {
row.add(nums[i]);
res.add(row);
}
// Comparison between current value and historical value , Put it after the code block , use i and i+1, because i Executed
// while (i <= len - n - 1 && nums[i] == nums[i + 1]) {
// i++;
// }
}
}
return res;
}
}
边栏推荐
- Rce code and Command Execution Vulnerability
- [数学建模] 微分方程--捕鱼业的持续发展
- Nacos TC setup of highly available Seata (02)
- 从0到1建设智能灰度数据体系:以vivo游戏中心为例
- Zynq learning notes (3) - partial reconfiguration
- Imperial cms7.5 imitation "D9 download station" software application download website source code
- 集合详解之 Collection + 面试题
- Upload nestjs configuration files, configure the use of middleware and pipelines
- Postman Association
- 浅谈镜头滤镜的类型及作用
猜你喜欢
[lgr-109] Luogu may race II & windy round 6
Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
Rce code and Command Execution Vulnerability
Simple understanding of interpreters and compilers
Principle and performance analysis of lepton lossless compression
【LGR-109】洛谷 5 月月赛 II & Windy Round 6
Yyds dry inventory SSH Remote Connection introduction
Postman前置脚本-全局变量和环境变量
Postman Association
acwing周赛58
随机推荐
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
Postman管理测试用例
Quelques conseils communs sur l'inspecteur de l'unit é, généralement pour les extensions d'éditeur ou d'autres
Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
What should the project manager do if there is something wrong with team collaboration?
ORM aggregate query and native database operation
Collection + interview questions
Programmers' position in the Internet industry | daily anecdotes
Redis 排查大 key 的4种方法,优化必备
组播和广播的知识点梳理
Huawei equipment is configured with OSPF and BFD linkage
Review of double pointer problems
Mysql高级篇学习总结9:创建索引、删除索引、降序索引、隐藏索引
Extension of graph theory
[lgr-109] Luogu may race II & windy round 6
Realize a binary read-write address book
F12 solve the problem that web pages cannot be copied
Yolov5 tensorrt acceleration
2021 robocom world robot developer competition - undergraduate group (semi-finals)
Three. JS learning - light and shadow (understanding)