The Solution to LeetCode 15 3Sum
来源:互联网 发布:自动填写表单软件 编辑:程序博客网 时间:2024/06/05 02:32
Question:
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.
这里的Note我在一开始想算法的时候没注意到,好像结果里边出现了重复的三个数,先贴上我的代码,不管啦!!这个改进问题留在下篇好了,警示自己先把题目读完,没读完就造成这种后果啦。再说说思路吧,看到给出的例子,我就按照例子来想方法,思考过程的图片如下……
Answer:
class Solution {public: vector<vector<int> >* r; vector<vector<int>> threeSum(vector<int>& nums) { r= new vector<vector<int>>(); if(nums.size()<3) { return *r; } sort(nums.begin(), nums.end()); int i=0; int j=1; int p=2; for (i=0,j=1;j<nums.size()-1;i++,j++) { for(p=2;p<nums.size();p++) { if(nums[i]+nums[j]+nums[p]==0) { vector<int> tmp; tmp.push_back(nums[i]); tmp.push_back(nums[j]); tmp.push_back(nums[p]); r->push_back(tmp); } } } return *r; }};
Run Code Result:
Your input
[-1,0,1,2,-1,-4]
Your answer
[[-1,-1,2],[-1,0,1],[0,1,-1]]
Expected answer
[[-1,-1,2],[-1,0,1]]
0 0
- The Solution to LeetCode 15 3Sum
- The Solution to LeetCode 15 3Sum改进版
- [LeetCode] 3Sum Solution
- [LeetCode] 3 Sum, Solution
- [LeetCode] Sum Root to Leaf Numbers, Solution
- [LeetCode] 3Sum Closest, Solution
- The Solution to LeetCode 120 Triangle
- The Solution to LeetCode 69 Sqrt(x)
- The Solution to Leetcode 136 Single Number
- The Solution to Leetcode 344 Reverse String
- The Solution to Leetcode 55 Jump Game
- The Solution to Leetcode 101 Symmetric Tree
- The Solution to Leetcode 268 Missing Number
- The Solution to Leetcode 463 Island Perimeter
- 3Sum | LeetCode O(N*N) Solution
- [LeetCode] 4Sum Solution
- [LeetCode] Combination Sum, Solution
- [LeetCode] Two Sum, Solution
- 反射的基本原理
- 在mac系统下配置环境变量
- ListView中item点击事件和item中radiobutton的点击editText输入焦点问题
- 【数据分析】图书馆数据-01建表
- 【Android】View事件分发思维导图
- The Solution to LeetCode 15 3Sum
- C#分布式云平台功能及使用说明
- myeclipse安装jdk
- js 操作当前鼠标点击的 事件 解决 div ul 下拉框事件
- 【上机笔试之六】Hash应用
- java中深拷贝和浅拷贝
- POJ 1230 Pass-Muraille (贪心)
- Java-IO笔记
- Android 漏洞分析入门 (一)