leetcode-3Sum
来源:互联网 发布:youtube免费翻墙软件 编辑:程序博客网 时间:2024/06/05 20:33
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
分析:先排序,按序取a,用two sum的方法求出b+c = -a;
class Solution {public: vector<vector<int> > threeSum(vector<int> &num) { int n = num.size(); vector<vector<int> > ret; if(n < 3)return ret; sort(num.begin(),num.end()); for(int i = 0; i < n-1; i++) { if((i > 0)&&(num[i] == num[i-1]))continue; int a = 0-num[i]; int j = i+1; int k = n-1; while(k > j) { if(a == num[j]+num[k]) { vector<int> temp; temp.push_back(num[i]); temp.push_back(num[j]); temp.push_back(num[k]); ret.push_back(temp); k--; j++; while((num[j]==num[j-1])&&(j < n))j++; while((num[k]==num[k+1])&&(k > -1))k--; } else if(a > num[j]+num[k])j++; else k--; } } return ret; }};
0 0
- 【Leetcode】3Sum (Sum)
- Leetcode:2Sum,3Sum
- 【Leetcode】3Sum Closest (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 3Sum
- LeetCode: 3 Sum Closest
- leetcode - 3 Sum
- leetcode - 3 sum closest
- leetcode 3Sum
- leetcode 3Sum Closest
- LeetCode: 3Sum
- 常用字符串解析与处理方法
- HTTP代理原理以及HTTP隧道技术
- aspnet_regsql在哪里 怎么运行它 以及功能介绍
- SQL SERVER 2005 数据库状态为“可疑”的解决方法
- Sqlite中使用SQL与其他数据库的区别
- leetcode-3Sum
- overridePendingTransition无效果解决方案
- Linux 的多线程编程的高效开发经验
- BZOJ 1493 NOI 2007 项链工厂 Splay
- SAP SD 发票分割 Invoice Split
- java二维码生成与解析代码实现
- 菜鸟版JAVA设计模式—从火锅底料到装饰器模式
- Eclipse Class Decompiler——Java反编译插件
- 2015创发科技校园招聘笔试题——把矩阵顺时针旋转90度