当前位置:网站首页>力扣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;
}
}
边栏推荐
- FPGA:生成固化文件(将代码固化到板子上面)
- 云渲染的应用正在扩大,越来越多的行业需要可视化服务
- QoS Quality of Service Seven Switch Congestion Management
- flex&bison系列第一章:flex Hello World
- 从企业的视角来看,数据中台到底意味着什么?
- Keras深度学习实战(17)——使用U-Net架构进行图像分割
- 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.
- JVM基本结构
- 第14章_MySQL事务日志
猜你喜欢
位算符详解 按位与、或、异或、取反、左移、右移
MySQL安装步骤
如何通过JMobile软件实现虹科物联网HMI/网关的报警功能?
常见端口及服务
FPGA:生成固化文件(将代码固化到板子上面)
redis.exceptions.DataError: Invalid input of type: ‘dict‘. Convert to a byte, string or number first
API 网关的功能
【Knowledge Sharing】What is SEI in the field of audio and video development?
QoS Quality of Service Six Router Congestion Management
MSE 治理中心重磅升级-流量治理、数据库治理、同 AZ 优先
随机推荐
工业基础类—利用xBIM提取IFC几何数据
RS-485多主机通信的组网方式评估
基于GAMS的电力系统优化分析
GBASE 8s 高可用RSS集群搭建
pytorch使用Dataloader加载自己的数据集train_X和train_Y
CEO对今天的CIO们真正的要求是什么?
365天挑战LeetCode1000题——Day 053 求解方程 解析 模拟
StoneDB 文档捉虫活动第一季
Unity_Stack<T>()的应用(多个次级界面后的返回逻辑)
Modern Privacy-Preserving Record Linkage Techniques: An Overview论文总结
openssl查看证书信息
弘玑Cyclone与风变科技达成战略合作:优势互补聚焦数字化人才培养
flask装饰器版登录、session
优化是一种习惯●出发点是'站在靠近临界'的地方
【Knowledge Sharing】What is SEI in the field of audio and video development?
状态压缩dp蒙德里安的梦想
常量
CAS:190598-55-1_Biotin sulfo-N-hydroxysuccinimide ester生物素化试
基于TCP的聊天系统
Optimization is a habit The starting point is to 'stand close to the critical'