The Solution to LeetCode 15 3Sum改进版
来源:互联网 发布:兼职淘宝客服好不好做 编辑:程序博客网 时间:2024/05/29 12:56
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.
上一篇的这道题的解答有点问题,结果中出现了冗余,本来想在上篇的代码的基础上做出改进,直接写出去掉冗余结果的代码,但是没 试成功,网上看了看别人对这道题的思路,有一点点启发,根据所给的例子,我的思路如下图:
Answer:
class Solution {public: vector<vector<int> >*r; vector<vector<int>> threeSum(vector<int>& nums) { r= new vector<vector<int>>(); sort(nums.begin(), nums.end()); for(int i = 0; i<nums.size(); i++) { //跳过相同的i while(i>0 && i<nums.size ()&& nums[i] == nums[i-1]) i++; int j = i + 1; int p = nums.size()- 1; while(j < 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); j ++; p --; //跳过相同的j while(j < p && nums[j] == nums[j-1]) j ++; //跳过相同的p while(p> j && nums[p] == nums[p+1]) p --; } else if(nums[i] + nums[j] + nums[p] < 0) { j ++; //跳过相同的j while(j < p && nums[j] == nums[j-1]) j ++; } else { p --; //跳过相同的p while(p > j && nums[p] == nums[p+1]) p --; } } } return *r; } };
Run Code Result:
Your input
[-1,0,1,2,-1,-4]
Your answer
[[-1,-1,2],[-1,0,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
- android数据库 Realm
- [软件测试]
- char数组的sizeof
- 剑指offer(二)java
- nyoj2-括号配对问题
- The Solution to LeetCode 15 3Sum改进版
- spring 定时任务cron在线表达式生成
- 小球在矩形框内45°碰撞问题
- Web窗体中的@page指令中各个字段的意思
- python3.6 sqlalchemy安装与使用
- 解决UnicodeEncodeError: 'ascii' codec can't encode characters in position 转自:http://cooler1217.iteye.c
- Python使用difflib对比两个文件操作实例
- 一个简单的登录,POST表单提交时报错,403 bad or missing token!
- Ubuntu中Vmware Tools的安装与卸载 <一>