LeetCode 3Sum
来源:互联网 发布:濒死状态知乎 编辑:程序博客网 时间:2024/06/06 21:00
题目:
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)思想:首先将数组进行排序,复杂度O(nlgn);然后固定一个数,问题就退化成2sum,复杂度O(n^2)。
class Solution {public: vector<vector<int> > threeSum(vector<int> &num) { int len = num.size(); vector<vector<int>> res; //O(nlgn) sort(num.begin(), num.end()); vector<int> tmp(3, INT_MIN); //O(n^2) for(int i = 0; i < len-2; i++) { //之前计算过的无需再计算 if(num[i] == tmp[0]) continue; tmp[0] = num[i]; int begin = i+1, end = len-1, target = 0 - num[i];while(begin < end) {int sum = num[begin] + num[end];if(sum == target) {tmp[1] = num[begin];tmp[2] = num[end];res.push_back(tmp);begin++;end--;continue;}else if(target > sum)begin++;elseend--;} } //使用set的目的是去重 set<vector<int>> ans(res.begin(), res.end()); res.clear(); res.insert(res.begin(), ans.begin(), ans.end()); return res; }};
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
- OpenGL学习笔记---黑屏解决2
- Android通过Get方式提交数据以及乱码处理
- struts2 2-ognl
- 第三周作业——冒泡排序和归并排序
- Ibatis2.0使用说明(一)——入门实例篇
- LeetCode 3Sum
- struts2 3-tags
- Ibatis2.0使用说明(二)——配置篇(1)
- ubuntu12.04.4默认壁纸路径
- unable to authenticate the package:8999887.itmsp / all transports failed diagnostics
- Ibatis2.0使用说明(二)——配置篇(2)
- Python IDLE快捷键一览
- struts2 4-结尾篇
- Error处理:Internal Error (classFileParser.cpp:3494)