当前位置:网站首页>力扣——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;
}
}边栏推荐
- Concepts of cloud-native applications and 15 characteristics of cloud-native applications
- 重建丢失的数据
- MySQL查询性能优化
- 反转链表-迭代反转法
- 小心 transmittable-thread-local 的这个坑
- Add the device library after Vivado installation
- 【CVA估值训练营】如何快速读懂上市公司年报——第五讲
- 解码Redis最易被忽视的CPU和内存占用高问题
- Matlab基础(2)——向量与多项式
- External Force Estimation Based on Time Delay Estimation with Perturbed Kalman Filter
猜你喜欢

Interviewer: Redis bloom filter and the cuckoo in the filter, how much do you know?

Redis master-slave replication

A tutorial on how to build a php environment under win

【Kaggle:UW-Madison GI Tract Image Segmentation】肠胃分割比赛:赛后复盘+数据再理解
![[BJDCTF2020]Cookie is so stable-1|SSTI injection](/img/48/34955bbe3460ef09a5b8213c7cc161.png)
[BJDCTF2020]Cookie is so stable-1|SSTI injection

C# 枚举类型 于xaml 中区别

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

别被隐私计算表象骗了 | 量子位智库报告(附下载)

Win11打不开exe应用程序怎么办?Win11无法打开exe程序解决方法

重建丢失的数据
随机推荐
Matlab绘图(1)——二维绘图
Unity Beginner 6 - Simple UI production (blood bar production) and audio addition and NPC dialogue bubbles (2d)
Redis master-slave replication
嵌入式环境下并发控制与线程安全
shell的理解
nodeJs--fs模块
【MySQL系列】-B+树索引和HASH索引有什么区别
Vivado安装后添加器件库
What happened when the computer crashed?
微信视频号视频如何下载提取?视频号直播回放如何下载?方法很简单!
Zhou Hongyi: Microsoft copied the 360 security model and became the largest security company in the United States
反转链表-递归反转法
New:WebKitX ActiveX :::Crack
关于File文件的相关知识
Underwater target detection method based on spatial feature selection
LeetCode_236_Last Common Ancestor of a Binary Tree
英 文 换 行
电脑奔溃的时候,到底发生了什么?
Matlab基础(5)——符号运算
概率论的学习整理2:如何对随机实验的对象:“事件” 进行计数呢? 四种计数方法,不只是排列组合