当前位置:网站首页>每日一题-三数之和-0716(2)
每日一题-三数之和-0716(2)
2022-08-05 05:17:00 【菜鸡程序媛】
题目:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
思路:
- 先将数组排序(方便排除后面会重复的三元组)
- 是动态的指针哦,一个固定在最左面,两个一个在左面+1,一个在右面,判断三个数字的和来移动指针
- 如果出现和相等的三个数字,就要开始排除后面会重复的三元组
while((i < j) && (nums[i] == nums[++ i]));
while((j > i) && (nums[j] == nums[-- j]));
代码:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
if(nums == null || nums.length < 3)
return null;
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i <= nums.length - 3; i ++){
// 当前的数字已经大于0,后续没必要走了
if(nums[i] > 0)
break;
// 已经和之前的数字相等了
if((i > 0) && nums[i] == nums[i - 1])
continue;
int j = i + 1;
int k = nums.length - 1;
while(j < k){
int sum = nums[i] + nums[j] + nums[k];
if(sum < 0){
while((j < k) && nums[j] == nums[++ j]);
}else if(sum > 0){
while((j < k) && nums[k] == nums[-- k]);
}else{
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[k]);
res.add(list);
// 如果还是相等的j的话 已经添加过了 没必要重复使用
while((j < k) && nums[j] == nums[++ j]);
//j已经变了,k已经不满足相加等于和了,自然要向前走了
while((j < k) && nums[k] == nums[-- k]);
}
}
}
return res;
}
}
边栏推荐
猜你喜欢

【UiPath2022+C#】UiPath 练习和解决方案-变量、数据类型和控制流程

It turns out that the MAE proposed by He Yuming is still a kind of data enhancement

【UiPath2022+C#】UiPath If条件语句

Redis设计与实现(第一部分):数据结构与对象

五、请求处理—Rest映射是怎样实现的?

The University of Göttingen proposed CLIPSeg, a model that can perform three segmentation tasks at the same time

网络信息安全运营方法论 (中)

MySQL主从复制—有手就能学会的MySQL集群搭建教程

【Multisim仿真】直流稳压电源设计报告

多边形等分
随机推荐
【ts】typescript高阶:条件类型与infer
电子产品量产工具(5)- 页面系统实现
用GAN的方法来进行图片匹配!休斯顿大学提出用于文本图像匹配的对抗表示学习,消除模态差异!
2021电赛资源及经验总结
【ts】typescript高阶:映射类型与keyof
基于STM32F407的WIFI通信(使用的是ESP8266模块)
CVPR 2020 - 频谱正则化
[Kaggle project actual combat record] Steps and ideas sharing of a picture classification project - taking leaf classification as an example (using Pytorch)
Service
Redis设计与实现(第二部分):单机数据库的实现
Machine Learning (1) - Machine Learning Fundamentals
十一、拦截器运行原理
5G中切片网络的核心技术FlexE
如何组织一场安全、可靠、高效的网络实战攻防演习?
深度学习系列(二)优化器 (Optimization)
电子产品量产工具(1)- 显示系统实现
dataframe 常用操作
OSPF网络类型
LeetCode刷题之第701题
三、自动配置源码分析