8: 3sum
来源:互联网 发布:图哈切夫斯基 知乎 编辑:程序博客网 时间:2024/06/06 10:07
注:本题的解法思想及参考的代码来自于https://github.com/soulmachine/leetcode#leetcode题解
题目: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(n^2)
解题代码如下:
class Solution {public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> result; if (nums.size() < 3) return result; sort(nums.begin(), nums.end()); const int target = 0; auto last = nums.end(); for (auto i = nums.begin(); i != last - 2; ++i) { auto j = i + 1; if (i > nums.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(vector<int>{*i, *j, *k}); ++j; --k; while (*j == *(j - 1) && j < k) ++j; while (*k == *(k + 1) && j < k) --k; } } } return result; }};
0 0
- 2.1.8 3Sum
- 8: 3sum
- Two Sum && 3 Sum
- 【Leetcode】3Sum (Sum)
- Array(8) -- Search Insert Position,3Sum,4Sum
- 3Sum 3Sum Closest 4Sum
- 3Sum & 3Sum Closest & 4Sum
- 3sum、3Sum closet、 4sum
- 3Sum, 3Sum Closest, 4 Sum
- leetcode 2 sum 3sum 4sum
- 2Sum 3Sum 4Sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- 3Sum
- 3SUM
- 3-sum
- 3Sum
- oj-5-字符串后移
- 设计模式原则详解
- 面试时关于c++方面的一些收获
- leetcode 476 Number Complement C++
- RHEL 7配置HAProxy实现Web负载均衡
- 8: 3sum
- FZU 2150 Fire Game(双端bfs搜索)
- 重构与模式:改善代码三部曲中的第三部
- 二叉树-创建、重建、转化
- 超实用!常用开源许可证有啥区别。
- Is the American Dream Really Dead?
- 58到家数据库30条军规解读
- 1079. Total Sales of Supply Chain (25)
- 解决Android Studio安装后运行出错的两个问题:dose not...和Internal error...