当前位置:网站首页>力扣——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;
}
}边栏推荐
- 云原生应用的概念和云原生应用的 15 个特征
- [BJDCTF2020]Cookie is so stable-1|SSTI注入
- Redis master-slave replication
- 周鸿祎:微软抄袭了360安全模式 所以成为美国最大的安全公司
- Redis 主从复制
- shell的理解
- Kubernetes之本地存储
- 概率论的学习整理--番外1:可重复且无次序的计数公式C(n+k-1,k) 的例题 : 同时丢3个骰子,会有多少种情况?答案不是216而是56!
- Microsoft SQL server hacked, bandwidth stolen
- LeetCode_236_Last Common Ancestor of a Binary Tree
猜你喜欢

概率论的学习整理1: 集合和事件

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

北上广线下活动丨年底最不可错过的技术聚会都齐了

Rust 从入门到精通02-安装

概率论的学习整理3: 概率的相关概念

Manage reading notes upward

崩了,该来的终究躲不掉

Rust from entry to proficient 02-installation

contentDocument contentWindow, canvas, svg, iframe

Horizontal comparison of 5 commonly used registration centers, whether it is used for interviews or technical selection, is very helpful
随机推荐
Rust from entry to proficient 02-installation
【MySQL系列】-B+树索引和HASH索引有什么区别
Microsoft SQL server hacked, bandwidth stolen
什么是驱动程序签名,驱动程序如何获取数字签名?
崩了,该来的终究躲不掉
The method of judging the same variable without the if branch
基于声信道分析的电缆隧道人员定位技术
Flexible distribution parameters of mechanical system modeling and control of research and development
External Force Estimation Based on Time Delay Estimation with Perturbed Kalman Filter
Based on MySQL database, Redis cache, MQ message middleware, ES high availability scheme of search engine parsing
概率论的学习整理--番外2:和二项式,组合相关的杨辉三角
Niuke-TOP101-BM42
概率论的学习和整理7:理解期望和方差还是要回到随机试验本身,期望不是平均值,方差的公式不同情况不同
概率论得学习和整理6:概率的分布
限时招募!淘宝无货源副业,800/天,不限经验,男女皆可,仅限前200名!
EXCEL解决问题:如何查找目标区域,是否包含指定字符串?
云原生应用的概念和云原生应用的 15 个特征
京东二面痛遭中间件虐杀,30天学透这套中间件小册,挺进阿里
Horizontal comparison of 5 commonly used registration centers, whether it is used for interviews or technical selection, is very helpful
Reverse linked list - iterative inversion method