当前位置:网站首页>力扣——15. 三数之和
力扣——15. 三数之和
2022-07-30 12:06:00 【weixin_54096215】
1.题目

2.思路
1.建立一个集合ArrayList()来存放每次sum=0的结果;
2.将数组根据升序的方式进行排序:nums.sort();
3.设置i=0,左右两个指针:left=i+1,right=nums.length()-1
4.条件判断1:如果集合中有重复的三元组则利用continue去除;
5.条件判断2:如果sum==0,则将其加入集合中,然后继续移动;
如果left(i)==left(i-1),则左指针继续右移,同理右指针左移。
如果sum<0,则左指针右移
自己的思路:思路差不多 但是好多细节的地方用代码还是不太会写,加油~
3.代码
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result =new ArrayList<>();
for(int i=0;i<nums.length-1;i++){
if(i>0 && nums[i] == nums[i-1]) continue;//为啥子?
int left=i+1;
int right=nums.length-1;
while(left<right){
int sum=nums[i]+nums[left]+nums[right];
if(sum == 0){
result.add(Arrays.asList(nums[i],nums[left],nums[right]));
left++;
right--;
while(left<right && nums[left]==nums[left-1]) left++;
while(left<right && nums[right]==nums[right+1]) right--;
}else if(sum<0)
left++;
else
right--;
}
}
return result;
}
}边栏推荐
- 概率论得学习整理--番外3:二项式定理和 二项式系数
- JD.com was brutally killed by middleware on two sides. After 30 days of learning this middleware booklet, it advanced to Ali.
- 多表联查的学习
- Apifox generates interface documentation tutorial and operation steps
- 【ASP.NET Core】选项类的依赖注入
- 2022-07-29 顾宇佳 学习笔记 异常处理
- [BJDCTF2020]Cookie is so stable-1|SSTI injection
- CMake库搜索函数居然不搜索LD_LIBRARY_PATH
- 别被隐私计算表象骗了 | 量子位智库报告(附下载)
- 基于声信道分析的电缆隧道人员定位技术
猜你喜欢

什么是驱动程序签名,驱动程序如何获取数字签名?

概率论的学习整理4:全概率公式

win下怎么搭建php环境的方法教程

Beijing, Shanghai and Guangzhou offline events丨The most unmissable technology gatherings at the end of the year are all gathered

概率论的学习整理--番外1:可重复且无次序的计数公式C(n+k-1,k) 的例题 : 同时丢3个骰子,会有多少种情况?答案不是216而是56!

Apifox generates interface documentation tutorial and operation steps

作业7.29 目录相关函数和文件属性相关函数

11 年膨胀 575 倍,微信为何从“小而美”变成了“大而肥”?

【记一个kaggle划水比赛】PetFinder.my - Pawpularity Contest 宠物预测

mapbox-gl开发教程(十四):画圆技巧
随机推荐
亚洲高校首现KDD博士论文奖:清华裘捷中获Runner Up奖,WINNER奖也是位华人
数字量输入输出模块DAM-5088
刷屏了!!!
CMake库搜索函数居然不搜索LD_LIBRARY_PATH
saltstack学习3模块
Niuke-TOP101-BM42
和数集团:让智慧城市更智慧,让现实生活更美好
EXCEL解决问题:如何查找目标区域,是否包含指定字符串?
概率论得学习和整理6:概率的分布
Rust 从入门到精通02-安装
概率论的学习整理5:贝叶斯(bayes)法则和贝叶斯概率
文本的对齐方式、行高、空间 等总结
京东二面痛遭中间件虐杀,30天学透这套中间件小册,挺进阿里
Scheduling of combined electric-heating system based on multi-objective two-stage stochastic programming method
The method of judging the same variable without the if branch
概率论的学习整理4:全概率公式
2022-07-29 顾宇佳 学习笔记 异常处理
Vivado安装后添加器件库
云原生应用的概念和云原生应用的 15 个特征
CMake库搜索函数居然不搜索LD_LIBRARY_PATH