Leetcode#15 3Sum
2015-07-05 22:12
253 查看
Difficulty:Medium
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.
折腾了好久终于debug出来了。
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)
折腾了好久终于debug出来了。
vector<vector<int> > threeSum(vector<int>& nums) { vector<vector<int> > ans; int len = nums.size(); sort(nums.begin(),nums.end()); for(int i = 0; i<len-2;i++){ int tar = 0 - nums[i]; int beg = i+1, en = len-1; if(nums[i]==nums[i-1]&&i>0) continue; while(en>beg){ if(nums[beg]==nums[beg-1]&&beg>i+1) {beg++; continue;} if(nums[en]==nums[en+1]&&en<len-1){ en--; continue;} if(nums[en]+nums[beg]<tar){ beg++; } else if(nums[en]+nums[beg]>tar){ en--; } else { vector<int> tmp; tmp.push_back(nums[i]); tmp.push_back(nums[beg]); tmp.push_back(nums[en]); ans.push_back(tmp); //cout<<"结果:"<<nums[i]<<" "<<nums[beg]<<" "<<nums[en]<<" "<<endl; beg++; } } } return ans; }
相关文章推荐
- 黑客丛林之旅通关攻略(共14关)
- Xcode的debug调试
- Getting Started with Activity & Fragment Transitions
- NYOJ 96 n-1位数(水题,%*符的学习与使用)
- 常用C++第三方库
- linux串口编程 非规范模式 read()问题
- android发送xml信息到web服务器简单例子
- 15-07-02 if 语句-猜拳游戏
- 正则表达式的概述
- Codeforces 451 B. Sort the Array
- 为什么innodb表最大支持64TB
- OOM android
- HDU 1407测试你是否和LTC水平一样高
- UVA 658 It's not a Bug, it's a Feature! (最短路,经典)
- map, hash_map,unordered_map
- javaSE学习笔记之IO
- HDUoj2214
- ZOJ 2760 How Many Shortest Path 最大流+Floyed
- STL使用总结
- 视频框架Vitamio学习