当前位置:网站首页>力扣——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;
}
}边栏推荐
- 别被隐私计算表象骗了 | 量子位智库报告(附下载)
- 小心 transmittable-thread-local 的这个坑
- 概率论得学习整理--番外3:二项式定理和 二项式系数
- 13-GuliMall Basics Summary
- 基于声信道分析的电缆隧道人员定位技术
- 反转链表-递归反转法
- Horizontal comparison of 5 commonly used registration centers, whether it is used for interviews or technical selection, is very helpful
- 数字量输入输出模块DAM-5088
- 刷屏了!!!
- 亚洲高校首现KDD博士论文奖:清华裘捷中获Runner Up奖,WINNER奖也是位华人
猜你喜欢
随机推荐
The method of judging the same variable without the if branch
What happened when the computer crashed?
JS事件参数对象event
C#调用explorer.exe打开指定目录
Get the original data API on 1688app
数据湖(十八):Flink与Iceberg整合SQL API操作
概率论的学习整理--番外1:可重复且无次序的计数公式C(n+k-1,k) 的例题 : 同时丢3个骰子,会有多少种情况?答案不是216而是56!
SQL 根据时间范围查询数据
2022-07-29 顾宇佳 学习笔记 异常处理
LinkedList与链表
Mysql索引结构
基于空间特征选择的水下目标检测方法
概率论的学习整理1: 集合和事件
基于多目标两阶段随机规划方法的电热联合系统调度
Reverse linked list - iterative inversion method
contentDocument contentWindow, canvas, svg, iframe
AlphaFold预测了几乎所有已知蛋白质!涵盖100万物种2.14亿结构,数据集开放免费用...
看了这些6G原型样机,我想一觉睡到2030年
单片机工程师笔试题目归纳汇总
【CVA估值训练营】如何快速读懂上市公司年报——第五讲








