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

4Sum #41

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

4Sum #41

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

Comments

@fkdl0048
Copy link
Owner

fkdl0048 commented Sep 29, 2024

// 3sum이랑 비슷하게 정렬하고, 포인터 생성해서 구하기?

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

        if (n < 4)  return result;

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

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

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

                    if (sum == target){
                        result.push_back({nums[i], nums[j], 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 < target){
                        left++;
                    }
                    else{
                        right--;
                    }
                }
            }
        }
        
        return result;
    }
};
  • 브루트 포스와 3Sum의 투포인터 방식을 조합해서 푼 문제 속도를 높이기 위해서 예외 처리나, 중복 제거등이 필수적이다.
  • 정수 승격(Integer Promotion)개념 추가, 산술연산에서 피연사자만 형변환을 하면 나머지도 자동으로 변환된다.
@fkdl0048 fkdl0048 mentioned this issue Sep 29, 2024
7 tasks
@fkdl0048 fkdl0048 self-assigned this Sep 29, 2024
@fkdl0048 fkdl0048 added this to Todo Sep 29, 2024
@github-project-automation github-project-automation bot moved this to Todo in Todo Sep 29, 2024
@fkdl0048 fkdl0048 moved this from Todo to Two-Week Plan in Todo Sep 29, 2024
@fkdl0048 fkdl0048 added this to the LeetCode milestone Sep 29, 2024
@github-project-automation github-project-automation bot moved this from In Progress to Done in Todo Sep 30, 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