[LeetCode15]3Sum
来源:互联网 发布:知乎和百度有什么区别 编辑:程序博客网 时间:2024/06/01 08:18
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(n2)。
这个方法可以推广到 k-sum,先排序,然后做 k − 2 次循环,在最内层循环左右夹逼,
时间复杂度是 O(max{n log n, nk−1})。
class Solution15{public:vector<vector<int>>threeSum(vector<int>& num){vector<vector<int>> result;if (num.size() < 3) return result;sort(num.begin(), num.end());const int target = 0;/*vector<int>::iterator iter;for (iter = num.begin(); iter != num.end(); iter++){cout << *iter << endl;}*/auto last = num.end();for (auto i = num.begin(); i < last - 2; ++i){auto j = i + 1;if (i>num.begin() && *i == *(i - 1)) continue;auto k = last - 1;while (j < k){if (*i + *j + *k < target){++j;while (*j == *(j - 1) && j < k)++j;}else if (*i + *j + *k>target){--k;while (*k == *(k + 1) && j < k)--k;}else{result.push_back({ *i, *j, *k });++j;--k;while (*j == *(j - 1) && *k == *(k + 1) && j < k)++j;}}}return result;}};int main15(){Solution15 solution;vector<int> vec = { -1, 0, 1, 2, -1, -4 };solution.threeSum(vec);getchar();return 0;}
0 0
- LeetCode15: 3 Sum
- LeetCode15:3Sum
- leetcode15 3Sum
- leetcode15 3Sum
- LeetCode15:3Sum
- leetcode15 3sum
- [LeetCode15]3Sum
- leetcode15---3Sum
- leetcode15.3Sum
- leetcode15:3Sum
- leetcode15:3Sum
- Leetcode15. 3Sum
- leetcode15. 3Sum
- leetcode15~3Sum
- leetcode15. 3Sum
- leetcode15. 3Sum
- LeetCode15. 3Sum
- leetcode15: 3Sum
- 内联标签和块标签
- Fragment第二次执行数据为空
- Android开发之创建Fragment
- 以人为本 | 如何保证高质量的软件交付
- swift 设置 navigation左右两侧按钮
- [LeetCode15]3Sum
- TCP/IP协议基本概括+ARP协议详解+DNS协议详解---Linux学习笔记
- [LeetCode] Remove Nth Node From End of List
- swift UITabBarController标签栏控制器
- CX3 使用GPIO来显示MIPI解析结果【新手入门手册】
- request method
- 生产消费者模式
- JS中的Map简单实现
- make iframe responsive and fullscreen iframe(支持iframe自适应,并全屏iframe)