当前位置:网站首页>LeetCode_2341_数组能形成多少数对
LeetCode_2341_数组能形成多少数对
2022-07-23 07:02:00 【Fitz1318】
题目链接
题目描述
给你一个下标从 0 开始的整数数组 nums 。在一步操作中,你可以执行以下步骤:
- 从
nums选出 两个 相等的 整数 - 从
nums中移除这两个整数,形成一个 数对
请你在 nums 上多次执行此操作直到无法继续执行。
返回一个下标从 0 开始、长度为 2 的整数数组 answer 作为答案,其中 answer[0] 是形成的数对数目,answer[1] 是对 nums 尽可能执行上述操作后剩下的整数数目。
示例 1:
输入:nums = [1,3,2,1,3,2,2]
输出:[3,1]
解释:
nums[0] 和 nums[3] 形成一个数对,并从 nums 中移除,nums = [3,2,3,2,2] 。
nums[0] 和 nums[2] 形成一个数对,并从 nums 中移除,nums = [2,2,2] 。
nums[0] 和 nums[1] 形成一个数对,并从 nums 中移除,nums = [2] 。
无法形成更多数对。总共形成 3 个数对,nums 中剩下 1 个数字。
示例 2:
输入:nums = [1,1]
输出:[1,0]
解释:nums[0] 和 nums[1] 形成一个数对,并从 nums 中移除,nums = [] 。
无法形成更多数对。总共形成 1 个数对,nums 中剩下 0 个数字。
示例 3:
输入:nums = [0]
输出:[0,1]
解释:无法形成数对,nums 中剩下 1 个数字。
提示:
1 <= nums.length <= 1000 <= nums[i] <= 100
解题思路
使用一个HashSet来遍历数组,对于一个元素来说,如果HashSet中包含了这个元素,那么就将数对数量加一,然后再将这个元素从HashSet中移除,最后剩下的经过数对操作后剩下的数目
AC代码
class Solution {
public int[] numberOfPairs(int[] nums) {
int num = 0;
HashSet<Integer> hashSet = new HashSet<>();
for (int i : nums) {
if (hashSet.contains(i)) {
hashSet.remove(i);
num++;
} else {
hashSet.add(i);
}
}
return new int[]{
num, nums.length - 2 * num};
}
}
边栏推荐
- Google play app store may delete the overview of APP permissions and use a new combination of data security information
- Day 11 notes
- Shell operator, $((expression)) "or" $[expression], expr method, condition judgment, test condition, [condition], comparison between two integers, judgment according to file permission, judgment accor
- Day 12 notes
- In depth interpretation of EVM's ecological Empire
- C language insert sort (direct insert sort)
- Debug No5 basic lighting
- 轻重链剖分/树链剖分
- ModuleNotFoundError: No module named ‘setuptools_ rust‘
- 【cocos creator】spine动画,监听播放结束
猜你喜欢

Day 11 notes

ES6——周考题

2022暑假软件创新实验室集训 项目实战1

MySQL index transaction & JDBC programming

Kotlin - Job 任务/取消

机器学习,吴恩达逻辑回归

Interface test - simple interface automation test demo
![Shell运算符、$((运算式))” 或 “$[运算式]、expr方法、条件判断、test condition、[ condition ]、两个整数之间比较、按照文件权限进行判断、按照文件类型进行判断](/img/65/a735ca2c2902e3fc773dda79438972.png)
Shell运算符、$((运算式))” 或 “$[运算式]、expr方法、条件判断、test condition、[ condition ]、两个整数之间比较、按照文件权限进行判断、按照文件类型进行判断

"Computing beast" Inspur nf5468a5 GPU server open trial free application
![[图形学]ASTC纹理压缩格式](/img/d1/734fe91d56716c610980696a8e0d06.png)
[图形学]ASTC纹理压缩格式
随机推荐
MySQL index transaction & JDBC programming
做测试如何应对新的开发模式?
Debug No5 basic lighting
php连接sql server
数据库系统原理与应用教程(048)—— MySQL 查询(十):自连接查询
数据库系统原理与应用教程(042)—— MySQL 查询(四):使用通配符构造查询条件
[Muduo] poller abstract class
关于this指针
QNX修改系统时间
In depth interpretation of EVM's ecological Empire
"Computing beast" Inspur nf5468a5 GPU server open trial free application
GLIB-CRITICAL g_file_test:assertion ‘filename != null‘ failed
docker redis
【MUDUO】EPOLLPOLLER事件分发器
Wu Enda machine learning series p31~p42
数据库系统原理与应用教程(051)—— MySQL 查询(十三):DML 语句中使用查询
[图形学]ASTC纹理压缩格式
【JS高级】正则入门基础—关于你想知道的正则表达式_01
Convergence of abnormal integral
SeekTiger的Okaleido有大动作,生态通证STI会借此爆发?