当前位置:网站首页>LeetCode15. 三数之和
LeetCode15. 三数之和
2022-04-23 06:41:00 【想进阿里的小菜鸡】
思路
使用双指针的方式进行。
首先对数组进行排序。
三个指针,一个当前元素指针i,一个左指针left,一个右指针right。
让i一次遍历数组下标,left=i+1;right = nums.length-1;temp = nums[i]+nums[left]+nums[right];当temp大于0时,就将right--;当temp小于0时就left++;当temp==0时就left++,right--;
遍历后的结果存在set中,set可以自动去除重复的元素。最后将set转为list即可。
代码
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
int left = 0;
int right = nums.length-1;
List<List<Integer>> res = new ArrayList<>();
Set<List<Integer>> t = new HashSet<>();
int temp = 0;
for(int i = 0;i<=right;i++){
left = i+1;
right = nums.length-1;
while(right>left){
temp = nums[i]+nums[left]+nums[right];
if( temp== 0){
t.add(Arrays.asList(nums[i], nums[left], nums[right]));
right--;
left++;
}else if(temp>0){
right--;
}else{
left++;
}
}
}
for(List l :t){
res.add(l);
}
return res;
}
}
版权声明
本文为[想进阿里的小菜鸡]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_56640241/article/details/124349909
边栏推荐
猜你喜欢
ABAP ALV显示金额与导出金额不一致
Chapter IV intangible assets
BUUCTF MISC刷题
CTF攻防世界刷题51-
使用 Ingress 实现金丝雀发布
攻防世界MISC刷题1-50
Intranet penetration series: icmptunnel of Intranet tunnel (by master dhavalkapil)
Sto with billing cross company inventory dump return
Ribbon启动流程
Intranet penetration series: pingtunnel of Intranet tunnel
随机推荐
MySQL--锁的奥秘--数据怎么锁
Ctf-misc learning from start to give up
Internal network security attack and defense: a practical guide to penetration testing (VII): cross domain attack analysis and defense
Online Safe Trajectory Generation For Quadrotors Using Fast Marching Method and Bernstein Basis Poly
Research on system and software security (5)
Research on system and software security (2)
数据库之Mysql——概述安装篇
攻防世界MISC刷题1-50
yum源仓库本地搭建的两种方法
Chapter IV intangible assets
内网渗透系列:内网隧道之dns2tcp
VBA調用SAP RFC實現數據讀取&寫入
Intranet penetration series: icmptunnel of Intranet tunnel (Master James Barlow's)
CTF attack and defense world brush questions 51-
SAP TR手动导入系统操作手册
About USB flash drive data prompt raw, need to format, data recovery notes
云计算赛项--2020年赛题基础部分[任务3]
Suggestions on university learning route planning
BUUCTF [极客大挑战 2019]EasySQL1
Concours de compétences en informatique en nuage - - première partie de l'environnement cloud privé openstack