3Sum
2015-08-07 23:48
239 查看
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.
Solution:
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)
Solution:
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int> > res; int len = nums.size(); if(len < 3) return res; sort(nums.begin(), nums.end()); for(int i = 0; i < len; ++i) { if(nums[i] > 0) break; if(i > 0 && nums[i] == nums[i-1]) continue; int sum = 0 - nums[i]; int left = i + 1, right = len - 1; vector<int> v; v.push_back(nums[i]); while(left < right) { int l = nums[left]; int r = nums[right]; if(l + r == sum) { v.push_back(l); v.push_back(r); res.push_back(v); v.pop_back(); v.pop_back(); while(nums[++left] == l) ; while(nums[--right] == r) ; } else if(nums[left] + nums[right] > sum) { while(nums[--right] == r) ; } else { while(nums[++left] == l) ; } } } return res; } };
相关文章推荐
- CryEngine3教程合辑
- Elasticsearch性能测试
- hahahaha
- iOS 枚举加位操作
- ACM 计算几何模板 点在三角形内 加强版 HDU4380
- TCP/IP详解学习笔记--TCP数据流
- PAT 1029. Median (25)
- jquey操作select
- HTML学习笔记(3)——CSS的引入,选择器和文本样式
- 添加Hyper-V群集主机到VMM服务器
- CSS字体设置
- Hive 之再认识
- playsms+kannel 配置过程中常见错误总结(1)
- JavaScript 编程
- C语言函数-指针
- unity代码反混淆
- 不见面的情侣要做到的七件事
- VMM服务器主机和主机组介绍
- AutoCAD常用快捷键
- python实现RSA加密算法