leetcode 15. 3Sum 二维vector

传送门

15. 3Sum

My Submissions

Question
Total Accepted: 108534 Total Submissions: 584814 Difficulty: Medium

Given an array S of n integers, are there elements abc 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 = ;i < n;i++){
if(i != && nums[i] == nums[i-]) continue;
for(j = i + ;j < n;j++){
if( (j != i + ) && (nums[j] == nums[j-]) ) continue;
for(k = j + ;k < n;k++){
if( (k != j+ ) && (nums[k] == nums[k-]) ) continue;
if(nums[i] + nums[j] + nums[k] == ){
tmp.clear();
tmp.push_back(nums[i]);tmp.push_back(nums[j]);tmp.push_back(nums[k]);
ans.push_back(tmp);
}
}
}
}
return ans;
}
};
上一篇:LeetCode 15 3Sum [sort]


下一篇:LeetCode 15. 三数之和(3Sum)