15. 3Sum
来源:互联网 发布:哪个软件直播笑傲江湖 编辑:程序博客网 时间:2024/04/30 13:50
Title
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]]
Solution
目前刷题,都用C++
2Sum问题的进一步3Sum,将其变为2Sum。
class Solution {public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> vb; if(nums.size() < 3) { return vb; } sort(nums.begin(), nums.end()); //几个小问题(却让略头疼...): // 1.a和a的下一位置元素值相同,跳过; // 2.b/c和b/c的下/前一位置元素相同,跳过; // 3.b和c相同,没问题。 for(decltype(nums.size()) i=0; i!=(nums.size()-2); ++i) { if(i != 0 && nums[i] == nums[i-1]){ continue; } auto a = nums[i]; auto b = nums.begin()+i+1; auto c = nums.end()-1; while(b != c) { if((*b+*c) == (-a)) { vector<int> v; v.push_back(a); //空vector,不可用下标去访问任何元素。 v.push_back(*b); //不可v[1] = *b; v.push_back(*c); // if(!(find(vb.begin(), vb.end(), v) != vb.end())) {//v not in vb // vb.push_back(v); // } //超时 vb.push_back(v); ++b; while(*b == *(b-1) && b!=c) { //跳过 ++b; } } else if((*b+*c) < (-a)) { ++b; while(*b == *(b-1) && b!=c) { ++b; } } else { --c; while(*c == *(c+1) && b!=c) { --c; } } } } return vb; }};
runtime: 64ms
之后再还有3Sum的变种等,以后再整。
0 0
- 15. 3Sum && 16 sum closet && 18 4sum
- 15. 3Sum 和 18. 4Sum
- 1. Two Sum&15. 3Sum
- LeetCode 15. 3Sum
- LeetCode --- 15. 3Sum
- [Leetcode] 15. 3Sum
- 【LeetCode】15. 3Sum
- 15. 3Sum
- 【leetcode】15. 3sum
- 【leetcode】15. 3Sum
- 15. 3Sum
- [leetcode] 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- leetcode 15. 3Sum
- OC篇--数据类型
- u-boot-2016.05移植:(5)、支持DM9000网卡
- 使用JDBC对数据库进行CRUD
- wireshark怎么抓包、wireshark抓包详细图文教程
- easyUI批量删除,向后台传数组
- 15. 3Sum
- 欢迎使用CSDN-markdown编辑器
- typeof和instanceof用法
- C++ String类实现以及初始化原理和析构顺序
- spring @Scheduled注解使用误区,强烈建议同胞们看。
- ARM LINUX 扩展串口
- 13个应用案例,讲述最真实的大数据故事!
- 网上面试题(二)
- 开发问题-Syntax error, insert ";" to complete FieldDeclaration