当前位置:网站首页>力扣18-四数之和——双指针法
力扣18-四数之和——双指针法
2022-08-10 19:01:00 【张怼怼√】
题目描述
给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。
求解思路
- 这道题目和三数之和就是一样的做法,就是在原来的基础上增加一层循环。
力扣15-三数之和——HashSet&双指针法力扣15-三数之和——HashSet
https://blog.csdn.net/weixin_44564247/article/details/126250012
只是在官方的测试用例中有一个超出边界的示例,所以需要将int类型转为long。
输入输出示例

代码
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
Set<List<Integer>> set = new HashSet<>();
for(int i = 0; i < nums.length; i++){
for(int j = i + 1; j < nums.length; j++){
int left = j + 1;
int right = nums.length - 1;
while(left < right){
if((long)nums[i] + nums[j] + nums[left] + nums[right] == target){
set.add(new ArrayList<>(Arrays.asList(nums[i] , nums[j] , nums[left] , nums[right])));
left++;
right--;
}else if((long)nums[i] + nums[j] + nums[left] + nums[right] <target){
left++;
}else right--;
}
}
}
List<List<Integer>> res = new ArrayList<>(set);
return res;
}
}边栏推荐
- 优化是一种习惯●出发点是'站在靠近临界'的地方
- 补坑简单图论题
- [Teach you how to do mini-games] How to lay out the hands of Dou Dizhu?See what the UP master of the 250,000 fan game area has to say
- 漫谈测试成长之探索——测试文档
- FPGA工程师面试试题集锦101~110
- 谈谈宝石方块游戏中的设计
- FEMRL: A Framework for Large-Scale Privacy-Preserving Linkage of Patients’ Electronic Health Rec论文总结
- Introduction to 3 d games beginners essential 】 【 modeling knowledge
- mysql 中大小写问题
- Today's bug, click on the bug that the Windows dynamic wallpaper disappears in the win10 taskbar, and no solution has been found yet.
猜你喜欢
随机推荐
PG中的Index-Only Scans解密
MySql main performance indicators description
Optimizing Bloom Filter: Challenges, Solutions, and Comparisons论文总结
LeetCode·283.移除零·双指针
#yyds干货盘点# 面试必刷TOP101:二分查找-I
When selecting a data destination when creating an offline synchronization node - an error is reported in the table, the database type is adb pg, what should I do?
30分钟使用百度EasyDL实现健康码/行程码智能识别
新建离线同步节点时选择数据去向-表时报错,数据库类型是adb pg,怎么办?
About npm/cnpm/npx/pnpm and yarn
Major upgrade of MSE Governance Center - Traffic Governance, Database Governance, Same AZ Priority
mysql 中大小写问题
What is the upstream bandwidth and downstream bandwidth of the server?
剖析Framework面试—>>>冲击Android高级职位
搭建自己的以图搜图系统 (一):10 行代码搞定以图搜图
2022-08-09 Study Notes day32-IO Stream
dumpsys meminfo 详解
Keras deep learning combat (17) - image segmentation using U-Net architecture
含有PEG 间隔基和一个末端伯胺基团(CAS:1006592-62-6)化学试剂
TikTok选品有什么技巧?
redis 事件








