3Sum
2016-07-13 21:24
246 查看
题目描述:
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: The solution set must not contain duplicate triplets.
解题思路:
首先对数组进行升序排序,然后遍历数组中的元素,固定当前遍历到的元素为第一个数,另外两个数一个从固定的数的后面一个开始,一个从数组的最后一个数开始,移动后两个数找到合适的三元组。
AC代码如下:
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: 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] ]
解题思路:
首先对数组进行升序排序,然后遍历数组中的元素,固定当前遍历到的元素为第一个数,另外两个数一个从固定的数的后面一个开始,一个从数组的最后一个数开始,移动后两个数找到合适的三元组。
AC代码如下:
class Solution{ public: vector<vector<int>> threeSum(vector<int>& nums){ vector<vector<int>> ans; if (nums.size() < 3) return ans; sort(nums.begin(), nums.end()); int n = nums.size(); for (int i = 0; i < n; ++i){ if (i>0 && nums[i] == nums[i - 1]) continue; //跳过重复的元素,避免结果中出现相同的三元组 int j = i + 1, k = n - 1; while (j < k){ int sum = nums[i] + nums[j] + nums[k]; if (sum == 0){ vector<int> tmp = { nums[i], nums[j], nums[k] }; ans.push_back(tmp); while (++j < k && nums[j] == nums[j - 1]); //跳过重复的元素,避免结果中出现相同的三元组 while (j < --k && nums[k] == nums[k + 1]); //跳过重复的元素,避免结果中出现相同的三元组 } else if(sum>0){ --k; } else{//sum<0 ++j; } } } return ans; } };
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析
- C与C++之间相互调用实例方法讲解