当前位置:网站首页>力扣——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;
}
}
边栏推荐
- The method of judging the same variable without the if branch
- win下怎么搭建php环境的方法教程
- 【32. 图中的层次(图的广度优先遍历)】
- int a=8,a=a++,a? int b=8,b=b+1,b?
- Apifox 生成接口文档 教程与操作步骤
- mapbox-gl开发教程(十四):画圆技巧
- Reverse linked list - iterative inversion method
- contentDocument contentWindow,canvas 、svg,iframe
- Scheduling of combined electric-heating system based on multi-objective two-stage stochastic programming method
- Verilog grammar basics HDL Bits training 08
猜你喜欢
概率论得学习和整理6:概率的分布
打破原则引入SQL,MongoDB到底想要干啥???
嵌入式环境下并发控制与线程安全
超图iServer rest服务之最佳路径分析
MySQL查询性能优化
Beijing, Shanghai and Guangzhou offline events丨The most unmissable technology gatherings at the end of the year are all gathered
历时两月,终拿字节跳动offer,算法面试题分享「带答案」
概率论的学习和整理7:理解期望和方差还是要回到随机试验本身,期望不是平均值,方差的公式不同情况不同
Rust 从入门到精通02-安装
概率论的学习整理2:如何对随机实验的对象:“事件” 进行计数呢? 四种计数方法,不只是排列组合
随机推荐
超图iServer rest服务之最佳路径分析
Verilog grammar basics HDL Bits training 08
概率论得学习和整理6:概率的分布
saltstack学习3模块
Horizontal comparison of 5 commonly used registration centers, whether it is used for interviews or technical selection, is very helpful
Bagging-Blending Multi-Model Fusion Short-Term Electricity Load Forecasting Based on Weighted Grey Correlation Projection
Underwater target detection method based on spatial feature selection
Homework 7.29 correlation function directory and file attributes related functions
最基础01/完全背包
反转链表-递归反转法
重建丢失的数据
看了这些6G原型样机,我想一觉睡到2030年
AlphaFold预测了几乎所有已知蛋白质!涵盖100万物种2.14亿结构,数据集开放免费用...
DOM常用方法以及项目
云原生应用的概念和云原生应用的 15 个特征
MySQL查询性能优化
作业7.29 目录相关函数和文件属性相关函数
LeetCode_235_Last Common Ancestor of Binary Search Tree
概率论的学习和整理7:理解期望和方差还是要回到随机试验本身,期望不是平均值,方差的公式不同情况不同
使用百度EasyDL实现明厨亮灶厨师帽识别