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

Max Number of K-Sum Pairs #81

Closed
Tracked by #101
fkdl0048 opened this issue Oct 12, 2024 · 0 comments
Closed
Tracked by #101

Max Number of K-Sum Pairs #81

fkdl0048 opened this issue Oct 12, 2024 · 0 comments
Assignees
Labels
Milestone

Comments

@fkdl0048
Copy link
Owner

fkdl0048 commented Oct 12, 2024

class Solution {
public:
    int maxOperations(vector<int>& nums, int k) {
        unordered_map<int, int> numCount;
        int operations = 0;

        for (int num : nums) {
            int complement = k - num;

            if (numCount[complement] > 0) {
                operations++;
                numCount[complement]--;
            } else {
                numCount[num]++;
            }
        }

        return operations;
    }
};
  • 해쉬맵으로 풀이하는 직관적인 방법
  • 다른 풀이를 보니 투 포인터로 푼 방법도 있어서 풀이해봄
class Solution {
public:
    int maxOperations(vector<int>& nums, int k) {
        int result = 0;
        int left = 0;
        int right = nums.size() - 1;

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

        while (left < right) {
            if (nums[left] + nums[right] == k) {
                result++;
                left++;
                right--;
            }
            else if (nums[left] + nums[right] > k) {
                right--;
            }
            else if (nums[left] + nums[right] < k) {
                left++;
            }
        }

        return result;
    }
};
  • 둘 다 좋은 풀이라고 생각..
@fkdl0048 fkdl0048 mentioned this issue Oct 12, 2024
7 tasks
@fkdl0048 fkdl0048 self-assigned this Oct 12, 2024
@fkdl0048 fkdl0048 added this to Todo Oct 12, 2024
@github-project-automation github-project-automation bot moved this to Todo in Todo Oct 12, 2024
@fkdl0048 fkdl0048 added this to the LeetCode milestone Oct 12, 2024
@fkdl0048 fkdl0048 moved this from Todo to Two-Week Plan in Todo Oct 12, 2024
@github-project-automation github-project-automation bot moved this from Two-Week Plan to Done in Todo Oct 13, 2024
@fkdl0048 fkdl0048 mentioned this issue Oct 15, 2024
75 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