Scribbling

[C++ Reminder] LeetCode: 15. 3Sum 본문

Computer Science/C++

[C++ Reminder] LeetCode: 15. 3Sum

focalpoint 2023. 1. 26. 09:33
#include <vector>
#include <algorithm>

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        
        using namespace std;
        sort(nums.begin(), nums.end());

        vector<vector<int>> ret;
        
        for (size_t i=0; i<nums.size()-2; i++) {
            if (i > 0 and nums[i] == nums[i-1]) {
                continue;
            }
            size_t j = i + 1, k = nums.size() - 1;
            while (j < k) {
                int num1 = nums.at(i), num2 = nums.at(j), num3 = nums.at(k);
                int summed = num1 + num2 + num3;
                if (summed == 0) {
                    vector<int> temp = {num1, num2, num3};
                    ret.push_back(temp);
                    while (j < k and nums[j] == num2) {
                        j += 1;
                    }
                    while (j < k and nums[k] == num3) {
                        k -= 1;
                    }
                } else if (summed < 0) {
                    j += 1;
                } else {
                    k -= 1;
                }
            }
        }
        return ret;
    }
};

'Computer Science > C++' 카테고리의 다른 글

[C++] 49. Group Anagrams  (0) 2023.08.18
[C++] LeetCode 242. Valid Anagram  (0) 2023.08.18
[C++] LeetCode 217. Contains Duplicate  (0) 2023.08.18
[C++ Reminder] LeetCode 2. Add Two Numbers  (0) 2023.01.23
[C++ Reminder] LeetCode 1. Two Sum  (0) 2023.01.23