난이도: Easy
Problem Description
You are given an integer array nums
consisting of 2 * n
integers.
You need to divide nums
into n
pairs such that:
- Each element belongs to exactly one pair.
- The elements present in a pair are equal.
Return true
if nums can be divided into n
pairs, otherwise return false
.
Problem Example
Example 1:
Input: nums = [3,2,3,2,2,2]
Output: true
Explanation:
There are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs.
If nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions.
Example 2:
Input: nums = [1,2,3,4]
Output: false
Explanation:
There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.
Constraints
nums.length == 2 * n
1 <= n <= 500
1 <= nums[i] <= 500
✏️ Solution
class Solution:
def divideArray(self, nums: List[int]) -> bool:
nums_count = Counter(nums)
return all(cnt % 2 == 0 for cnt in nums_count.values())
단순히 생각해보면 nums의 요소 중 같은 요소들을 세었을 때 짝수개 만큼 있으면 조건을 만족하면서 pair를 만들 수 있다.
따라서 Counter함수를 통해 nums의 요소를 세었다.
이 때, nums_count.value()에 값들 중 홀수가 있으면 False를 return하고 모두 짝수라면 True를 반환하면 된다.
⚙️ Runtime & Memory
문제: 2206. Divide Array Into Equal Pairs
깃허브: github
algorithmPractice/LeetCode/2308-divide-array-into-equal-pairs at main · laewonJeong/algorithmPractice
하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.
github.com
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 3108. Minimum Cost Walk in Weighted Graph (Python) (0) | 2025.03.20 |
---|---|
[LeetCode] 2401. Longest Nice Subarray (Python) (0) | 2025.03.18 |
[LeetCode] 2594. Minimum Time to Repair Cars (Python) (0) | 2025.03.16 |
[LeetCode] 2226. Maximum Candies Allocated to K Children (Python) (0) | 2025.03.14 |
[LeetCode] 2529. Maximum Count of Positive Integer and Negative Integer (Python) (0) | 2025.03.12 |