Maximum Number of Pairs in Array
We can utilize a dictionary to keep track of the occurrences of each integer in the nums
array. Then we can iterate through the dictionary to find the number of pairs that can be formed with each integer, and the number of leftovers for each integer. Finally, we can sum up these values to obtain the final result.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| from collections import Counter
class Solution:
def numberOfPairs(self, nums: List[int]) -> List[int]:
# Count the occurrences of each integer in nums
counts = Counter(nums)
# Initialize variables to keep track of the number of pairs and leftovers
pairs = 0
leftovers = 0
# Iterate through the counts dictionary
for count in counts.values():
# Determine the number of pairs and leftovers for the current integer
current_pairs = count // 2
current_leftovers = count % 2
# Update the total number of pairs and leftovers
pairs += current_pairs
leftovers += current_leftovers
return [pairs, leftovers]
|
The code first counts the occurrences of each integer using the Counter
class from the collections
module. Then it iterates through the counts to find the number of pairs and leftovers, and returns the result in the required format.