当前位置:网站首页>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
边栏推荐
- Complete color conversion formulas and conversion tables (31 kinds)
- KVM安装部署
- [NLP notes] preliminary study on CRF principle
- 攻防世界MISC刷题1-50
- Ctf-misc learning from start to give up
- 第七章 资产减值
- The displayed amount of ABAP ALV is inconsistent with the exported amount
- Research on system and software security (2)
- Talk about the essence of interface idempotent and consumption idempotent
- Mysql database backup and recovery under Linux (full + incremental)
猜你喜欢
内网渗透系列:内网隧道之dnscat2
使用 Ingress 实现金丝雀发布
Go语学习笔记 - 数组 | 从零开始Go语言
Three minutes to teach you to use Houdini fluid > > to solve particle fluid droplets
Research on software security based on NLP (I)
利用sqlmap注入获取网址管理员账号密码
CTF-MISC总结
MySQL -- the secret of lock -- how to lock data
Robust and Efficient Quadrotor Trajectory Generation for Fast Autonomous Flight
Research on software security based on NLP (2)
随机推荐
Ctf-misc summary
【编程实践/嵌入式比赛】嵌入式比赛学习记录(二):基于TCP的图片流传输
Online Safe Trajectory Generation For Quadrotors Using Fast Marching Method and Bernstein Basis Poly
Houdini > rigid body, rigid body breaking RBD
VBA調用SAP RFC實現數據讀取&寫入
Construction of middleman environment mitmproxy
随笔(不定时更新)
Ctf-misc learning from start to give up
Attack and defense world misc questions 1-50
Expression related to month, year and day in SVG
strcat()、strcpy()、strcmp()、strlen()
【编程实践/嵌入式比赛】嵌入式比赛学习记录(一):TCP服务器和web界面的建立
第四章 无形资产
《内网安全攻防:渗透测试实战指南》读书笔记(八):权限维持分析及防御
yum源仓库本地搭建的两种方法
Buuctf misc brush questions
Concours de compétences en informatique en nuage - - première partie de l'environnement cloud privé openstack
Export all SVG files in the specified path into pictures in PNG format (thumbnail or original size)
SAP GUI安全性
String self generated code within a given range