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>> ans;
sort(nums.begin(), nums.end());
int target, left, right, sum;
for (int i = 0; i < nums.size(); i++)
{
if (i > 0 && nums[i - 1] == nums[i]) continue;
target = -nums[i];
left = i + 1;
right = nums.size() - 1;
while (left < right)
{
sum = nums[left] + nums[right];
if (sum < target) left++;
else if (sum > target) right--;
else
{
ans.push_back({ nums[i], nums[left], nums[right] });
while (left < right && nums[left] == ans[ans.size() - 1][1]) left++;
while (left < right && nums[right] == ans[ans.size() - 1][2]) right--;
}
}
}
return ans;
}
};
'Challenge' 카테고리의 다른 글
[LeetCode] Letter Combinations of a Phone Number (0) | 2021.10.06 |
---|---|
[LeetCode] 3Sum Closest (0) | 2021.10.06 |
[Programmers] 이분탐색 - 징검다리 (0) | 2021.10.03 |
[Programmers] 이분탐색 - 입국심사 (0) | 2021.10.03 |
[Codility] MinAvgTwoSlice (0) | 2021.10.03 |