当前位置:网站首页>力扣——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;
}
}边栏推荐
- 【记一个kaggle划水比赛】PetFinder.my - Pawpularity Contest 宠物预测
- 基于加权灰色关联投影的Bagging-Blending多模型融合短期电力负荷预测
- [BJDCTF2020]Cookie is so stable-1|SSTI injection
- saltstack学习3模块
- DOM常用方法以及项目
- 备战金九银十!2022面试必刷大厂架构面试真题汇总+阿里七面面经+架构师简历模板分享
- 2022-07-29 Gu Yujia Study Notes Exception Handling
- Manage reading notes upward
- 多表联查的学习
- Horizontal comparison of 5 commonly used registration centers, whether it is used for interviews or technical selection, is very helpful
猜你喜欢
随机推荐
概率论的学习整理--番外1:可重复且无次序的计数公式C(n+k-1,k) 的例题 : 同时丢3个骰子,会有多少种情况?答案不是216而是56!
限时招募!淘宝无货源副业,800/天,不限经验,男女皆可,仅限前200名!
周鸿祎:微软抄袭了360安全模式 所以成为美国最大的安全公司
2022-07-29 Gu Yujia Study Notes Exception Handling
JD.com was brutally killed by middleware on two sides. After 30 days of learning this middleware booklet, it advanced to Ali.
Manage reading notes upward
Concepts of cloud-native applications and 15 characteristics of cloud-native applications
Farmers on the assembly line: I grow vegetables in a factory
13-GuliMall 基础篇总结
超图iServer rest服务之最佳路径分析
saltstack学习2grains&pillar
概率论的学习整理2:如何对随机实验的对象:“事件” 进行计数呢? 四种计数方法,不只是排列组合
PanGu-Coder: 函数级的代码生成模型
Horizontal comparison of 5 commonly used registration centers, whether it is used for interviews or technical selection, is very helpful
The method of judging the same variable without the if branch
Testability of Fuzzy Discrete Event Systems
【MySQL系列】-B+树索引和HASH索引有什么区别
多表联查的学习
什么是驱动程序签名,驱动程序如何获取数字签名?
EXCEL解决问题:如何查找目标区域,是否包含指定字符串?









