You are given a 0-indexed integer array nums. In one operation, you may do the following:
Choose two integers in nums that are equal.
Remove both integers from nums, forming a pair.
The operation is done on nums as many times as possible.
Return _a0-indexed integer array _answerof size2whereanswer[0]is the number of pairs that are formed andanswer[1]is the number of leftover integers innumsafter doing the operation as many times as possible.
Input: nums =[1,3,2,1,3,2,2]Output: [3,1]Explanation:
Form a pair with nums[0] and nums[3] and remove them from nums. Now, nums =[3,2,3,2,2].Form a pair with nums[0] and nums[2] and remove them from nums. Now, nums =[2,2,2].Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums =[2].No more pairs can be formed. A total of 3 pairs have been formed, and there is1 number leftover in nums.
Input: nums =[1,1]Output: [1,0]Explanation: Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums =[].No more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.
To maximize the number of pairs, count the frequency of each number. Each pair requires two equal numbers, so the number of pairs for each value is count // 2. The leftovers are the numbers that couldn’t be paired.
import java.util.*;
classSolution {
publicint[]numberOfPairs(int[] nums) {
Map<Integer, Integer> cnt =new HashMap<>();
for (int x : nums) cnt.put(x, cnt.getOrDefault(x, 0) + 1);
int pairs = 0, left = 0;
for (int v : cnt.values()) {
pairs += v / 2;
left += v % 2;
}
returnnewint[]{pairs, left};
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funnumberOfPairs(nums: IntArray): IntArray {
val cnt = mutableMapOf<Int, Int>()
for (x in nums) cnt[x] = cnt.getOrDefault(x, 0) + 1var pairs = 0var left = 0for (v in cnt.values) {
pairs += v / 2 left += v % 2 }
return intArrayOf(pairs, left)
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defnumberOfPairs(self, nums: list[int]) -> list[int]:
from collections import Counter
cnt = Counter(nums)
pairs = left =0for v in cnt.values():
pairs += v //2 left += v %2return [pairs, left]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::collections::HashMap;
impl Solution {
pubfnnumber_of_pairs(nums: Vec<i32>) -> Vec<i32> {
letmut cnt = HashMap::new();
for x in nums {
*cnt.entry(x).or_insert(0) +=1;
}
letmut pairs =0;
letmut left =0;
for&v in cnt.values() {
pairs += v /2;
left += v %2;
}
vec![pairs, left]
}
}