[LeetCode] 2341. Maximum Number of Pairs in Array
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 a 0-indexed integer array answer
of size 2
where answer[0]
is the number of pairs that are formed and answer[1]
is the number of leftover integers in nums
after doing the operation as many times as possible.
Example 1:
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 is 1 number leftover in nums.
Example 2:
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.
Example 3:
Input: nums = [0] Output: [0,1] Explanation: No pairs can be formed, and there is 1 number leftover in nums.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
数组能形成多少数对。
给你一个下标从 0 开始的整数数组 nums 。在一步操作中,你可以执行以下步骤:
从 nums 选出 两个 相等的 整数
从 nums 中移除这两个整数,形成一个 数对
请你在 nums 上多次执行此操作直到无法继续执行。返回一个下标从 0 开始、长度为 2 的整数数组 answer 作为答案,其中 answer[0] 是形成的数对数目,answer[1] 是对 nums 尽可能执行上述操作后剩下的整数数目。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-number-of-pairs-in-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是 counting sort。需要遍历两次 input 数组,第一次遍历我们用一个哈希表把每个不同元素的出现次数记录下来;第二次遍历的时候,遍历哈希表的 keyset,对于每个不同的 key,如果他的出现次数 % 2 == 0,则他是一个 pair;否则他最后一定有一个落单的。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int[] numberOfPairs(int[] nums) { 3 int pair = 0; 4 int leftOver = 0; 5 HashMap<Integer, Integer> map = new HashMap<>(); 6 for (int num : nums) { 7 map.put(num, map.getOrDefault(num, 0) + 1); 8 } 9 10 for (int num : map.keySet()) { 11 int val = map.get(num); 12 if (val % 2 == 1) { 13 leftOver++; 14 } 15 pair += val / 2; 16 } 17 18 int[] res = new int[2]; 19 res[0] = pair; 20 res[1] = leftOver; 21 return res; 22 } 23 }