250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code c++)3Sum 본문
728x90
반응형
15. 3Sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]]
Example 2:
Input: nums = [] Output: []
Example 3:
Input: nums = [0] Output: []
Constraints:
- 0 <= nums.length <= 3000
- -105 <= nums[i] <= 105
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> answer;
int size = nums.size();
if(nums.size() < 3){
return {};
}
sort(nums.begin(), nums.end());
for(int i = 0; i < size - 2; i++){
if(i > 0 && nums[i] == nums[i - 1]){
continue;
}
int j = i + 1;
int k = size - 1;
while(j < k){
int sum = nums[i] + nums[j] + nums[k];
if(sum == 0){
answer.push_back({nums[i], nums[j], nums[k]});
while(j < k && nums[j] == nums[j + 1]){
j++;
}
while(j < k && nums[k] == nums[k - 1]){
k--;
}
j++;
k--;
}
else if(sum < 0){
j++;
}
else{
k--;
}
}
}
return answer;
}
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code c++)LRU Cache (0) | 2021.08.23 |
---|---|
(Leet Code c++)FIrst Unique Character in a string (0) | 2021.08.16 |
(Leet Code c++)Ransom Note (0) | 2021.08.10 |
(Leet Code c++)Cuess Number Higher or Lower (0) | 2021.08.09 |
(Leet Code c++)Valid Perfect Square (0) | 2021.08.04 |