Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3Sum #38

Closed
Tracked by #100
fkdl0048 opened this issue Sep 28, 2024 · 0 comments
Closed
Tracked by #100

3Sum #38

fkdl0048 opened this issue Sep 28, 2024 · 0 comments
Assignees
Labels
Milestone

Comments

@fkdl0048
Copy link
Owner

fkdl0048 commented Sep 28, 2024

#include <vector>
#include <algorithm>

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> result;
        int n = nums.size();

        sort(nums.begin(), nums.end());

        for (int i = 0; i < n - 2; i++){
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            
            int left = i + 1;
            int right = n - 1;

            while (left < right){
                int sum = nums[i] + nums[left] + nums[right];

                if (sum == 0){
                    result.push_back({nums[i], nums[left], nums[right]});

                    while (left < right && nums[left] == nums[left + 1])
                        left++;
                    while (left < right && nums[right] == nums[right - 1])
                        right--;
                    
                    left++;
                    right--;
                }
                else if (sum < 0)
                    left++;
                else
                    right--;
            }
        }

        return result;
    }
};
  • 간단할 줄 알았는데, 여러운 문제... LeetCode에서 힌트를 볼 수 있었따니.. 이제 알았다.
  • 중복 제거가 핵심이고, 3개이기 때문에 투포인터라 푼다.
@fkdl0048 fkdl0048 mentioned this issue Sep 28, 2024
7 tasks
@fkdl0048 fkdl0048 self-assigned this Sep 28, 2024
@fkdl0048 fkdl0048 added this to Todo Sep 28, 2024
@github-project-automation github-project-automation bot moved this to Todo in Todo Sep 28, 2024
@fkdl0048 fkdl0048 added this to the LeetCode milestone Sep 28, 2024
@fkdl0048 fkdl0048 moved this from Todo to Two-Week Plan in Todo Sep 28, 2024
@github-project-automation github-project-automation bot moved this from Two-Week Plan to Done in Todo Sep 29, 2024
@fkdl0048 fkdl0048 mentioned this issue Oct 15, 2024
47 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Done
Development

No branches or pull requests

1 participant