当前位置:网站首页>每日一题-三数之和-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;
}
}
边栏推荐
猜你喜欢

AIDL detailed explanation
![[Database and SQL study notes] 9. (T-SQL language) Define variables, advanced queries, process control (conditions, loops, etc.)](/img/7e/566bfa17c5b138d1f909185721c735.png)
[Database and SQL study notes] 9. (T-SQL language) Define variables, advanced queries, process control (conditions, loops, etc.)

关于存储IOPS你必须了解的概念

伪RTOS-ProroThread在CH573芯片上的移植

leetCode刷题之第31题

LeetCode刷题之第416题

PoE视频监控解决方案
![[Pytorch study notes] 10. How to quickly create your own Dataset dataset object (inherit the Dataset class and override the corresponding method)](/img/71/f82e76085f9d8e6610f6f817e2148f.png)
[Pytorch study notes] 10. How to quickly create your own Dataset dataset object (inherit the Dataset class and override the corresponding method)

Detailed explanation of BroadCast Receiver (broadcast)

盘点关于发顶会顶刊论文,你需要知道写作上的这些事情!
随机推荐
TinyFlashDB:一种超轻量的可纠错的通用单片机flash存储方案
C语言程序死循环问题解析——变量被修改
C语言入门笔记 —— 初识
电子产品量产工具(5)- 页面系统实现
IT系统运行维护方法及策略
C语言入门笔记 —— 分支与循环
【UiPath2022+C#】UiPath数据类型
五、请求处理—Rest映射是怎样实现的?
浅谈遇到的小问题
【nodejs】第一章:nodejs架构
CVPR最佳论文得主清华黄高团队提出首篇动态网络综述
【论文阅读-表情捕捉】ExpNet: Landmark-Free, Deep, 3D Facial Expressions
【UiPath2022+C#】UiPath 数据操作
framebuffer应用编程及文字显示(1)
九、响应处理——内容协商底层原理
深度学习系列(二)优化器 (Optimization)
将一句话的单词进行倒置(C语言纯代码)
【ts】typescript高阶:分布式条件类型
最简单的防抖节流理解法
Service