首页 > 代码库 > [LeetCode] 3Sum
[LeetCode] 3Sum
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)
分析:如果使用三层循环的话肯定会Time Limited Exceeded的!
class Solution {public: vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > result; int n = (int)num.size(); if (n > 2) { sort(num.begin(), num.end()); for (int i = 1; i < n - 1; ++i) {//序号i为中间的数,序号l为较小的数,序号r为较大的数,每次循环时先固定一个中间的数i if (i > 2 && num[i] == num[i - 2]) continue; int l = 0, r = n - 1; while (l < i && r > i) { if (l > 1 && num[l] == num[l - 1]) { ++l; continue; } if (r < n - 1 && num[r] == num[r + 1]) { --r; continue; } int sum = num[l] + num[i] + num[r]; if (sum == 0) { vector<int> item; item.push_back( num[l]); item.push_back( num[i]); item.push_back( num[r]); bool flag = false; for (int j = 0; j < result.size(); ++j) { if (result[j][0] == num[l] && result[j][1] == num[i]) { flag = true; break; } } if (!flag) result.push_back(item); ++l; --r; } else if (sum < 0) ++l; else --r; }//end while }//end for }//end if return result; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。