博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode15.3Sum三数之和
阅读量:4346 次
发布时间:2019-06-07

本文共 889 字,大约阅读时间需要 2 分钟。

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]

 

 

双指针加去重

 

class Solution {public:    vector
> threeSum(vector
& nums) { int len = nums.size(); sort(nums.begin(), nums.end()); map
> check; vector
> res; for(int i = 0; i < len - 2; i++) { int low = i + 1; int high = len - 1; while(low < high) { if(nums[low] + nums[high] == -nums[i]) { res.push_back({nums[i], nums[low], nums[high]}); //去重 while(nums[low] == nums[low + 1]) low++; low++; } if(nums[low] + nums[high] > -nums[i]) { high--; } else { low++; } } //去重 while(nums[i] == nums[i + 1]) i++; } return res; }};

 

转载于:https://www.cnblogs.com/lMonster81/p/10433885.html

你可能感兴趣的文章
数据结构:栈 顺序表方法和单链表方法(python版)
查看>>
数据结构:优先队列 基于堆实现(python版)
查看>>
org.hibernate.exception.GenericJDBCException: could not execute statement
查看>>
GeoServer地图开发解决方案(一):环境搭建篇
查看>>
TypeScript的数据类型
查看>>
读写txt文件
查看>>
struct vs class in C++
查看>>
XHTML
查看>>
作业:------数据库下拉菜单,数据库复选框
查看>>
整合SSM
查看>>
web.xml中的welcome-file-list标签作用
查看>>
如何查看本机的oracle数据库的IP地址 和 数据库名
查看>>
oracle用户密码忘记怎么修改
查看>>
pl/sql修改data
查看>>
pom.xml文件中properties有什么用
查看>>
springboot @Select @Insert @Update @Delete
查看>>
idea中springboot静态资源及页面跳转问题
查看>>
渗透测试基础
查看>>
第四 五周结对作业(照片)
查看>>
HOJ 1898 Babelfish(Trie树)
查看>>