当前位置:网站首页>LeetCode_2357_使数组种所有元素都等于零
LeetCode_2357_使数组种所有元素都等于零
2022-08-02 08:19:00 【Fitz1318】
题目链接
题目描述
给你一个非负整数数组 nums
。在一步操作中,你必须:
- 选出一个正整数
x
,x
需要小于或等于nums
中 最小 的 非零 元素。 nums
中的每个正整数都减去x
。
返回使 nums
中所有元素都等于 0
需要的 最少 操作数。
示例 1:
输入:nums = [1,5,0,3,5]
输出:3
解释:
第一步操作:选出 x = 1 ,之后 nums = [0,4,0,2,4] 。
第二步操作:选出 x = 2 ,之后 nums = [0,2,0,0,2] 。
第三步操作:选出 x = 2 ,之后 nums = [0,0,0,0,0] 。
示例 2:
输入:nums = [0]
输出:0
解释:nums 中的每个元素都已经是 0 ,所以不需要执行任何操作。
提示:
1 <= nums.length <= 100
0 <= nums[i] <= 100
解题思路
- 具有相同值的元素将始终采用相同数量的操作才能变为 0。相反,具有不同值的元素将始终采用不同数量的操作才能变为 0。
- 对于数组中的元素,如果有
x
个不同的且不等于0
的元素,需要减x
次即可
AC代码
class Solution {
public int minimumOperations(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int i : nums) {
set.add(i);
}
if (set.contains(0)) {
return set.size() - 1;
} else {
return set.size();
}
}
}
边栏推荐
- pnpm:简介
- [ansible] playbook explains the execution steps in combination with the project
- Stop mental exhaustion Daily sharing
- Redisson实现分布式锁
- Redis分布式锁
- JSP页面中page指令有哪些属性及方法可使用呢?
- QT web 开发 - 笔记 - 3
- Biotin hydrazide HCl|CAS:66640-86-6|生物素-酰肼盐酸盐
- A young man with strong blood and energy actually became a housekeeper. How did he successfully turn around and change careers?
- MySQL ODBC驱动简介
猜你喜欢
随机推荐
unity pdg 设置隐藏不需要的节点以及实现自动勾选自动加载项
三维体尺测量
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之一:解题思路
What is the function of page directive contentPage/pageEncoding in JSP page?
Installation and use of pnpm
JSP页面中page指令contentPage/pageEncoding具有什么功能呢?
mysqldump --set-gtid-purged=OFF
Seleniu screenshots code and assign name to the picture
What is NoSQL?Databases for the cloud-scale future
High imitation [Huawei consumer business official website] and wonderful animation analysis: practice embedding JS code in low-code platform
tf中tensor的大小输出
Redisson的看门狗机制
Business Intelligence Platform BI Business Intelligence Analysis Platform How to Choose the Right Business Intelligence Platform BI
pnpm的安装与使用
etcd实现大规模服务治理应用实战
(Note) AXIS ACASIS DT-3608 Dual-bay Hard Disk Array Box RAID Setting
cas:139504-50-0 美登素DM1|Mertansine|
In a recent build figure SLAM, and locate the progress
Three types of [OC learning notes] Block
Biotin hydrazide HCl|CAS:66640-86-6|生物素-酰肼盐酸盐