알고리즘

Divide Array Into Equal Pairs

짬뽕얼큰하게 2025. 3. 17. 23:06

Leetcode Problem:

Summary

  • Check if an array of integers can be divided into pairs of equal numbers.

Approach

  • Count the occurrences of each number in the array and check if all counts are even
  • If any count is odd, return false
  • Otherwise, return true.

Complexity

  • O(n) where n is the length of the input array

Explanation

  • The solution first counts the occurrences of each number in the array using an array cnt
  • Then, it checks if all counts are even by iterating from 1 to 500
  • If any count is odd, it returns false
  • Otherwise, it returns true.

Solution Code:


class Solution {
public:
    int cnt[501] = {0};
    bool divideArray(vector& nums) {
        for(int n : nums){
            cnt[n]++;
        }
        for(int i = 1; i <= 500; i++){
            if(cnt[i] &1){
                return false;
            }
        }
        return true;
    }
};