您的位置:首页 > 其它

leetcode 15. 3Sum 二维vector

2016-03-24 16:45 666 查看
传送门

15. 3Sum

My Submissions
Question

Total Accepted: 108534 Total Submissions: 584814 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.

For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)


Subscribe to see which companies asked this question

Hide Tags
Array Two Pointers

Show Similar Problems

Submission Details

311 / 311 test cases passed.
Status:

Accepted

Runtime: 76 ms
Submitted: 0 minutes ago
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> tmp;
int n = nums.size();
sort(nums.begin(),nums.end());
int i,j,k;
for(i = 0;i < n;i++){
if(i != 0 && nums[i] == nums[i-1]) continue;
for(j = i + 1;j < n;j++){
if( (j != i + 1) && (nums[j] == nums[j-1]) ) continue;
for(k = j + 1;k < n;k++){
if( (k != j+1 ) && (nums[k] == nums[k-1]) ) continue;
if(nums[i] + nums[j] + nums[k] == 0){
tmp.clear();
tmp.push_back(nums[i]);tmp.push_back(nums[j]);tmp.push_back(nums[k]);
ans.push_back(tmp);
}
}
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: