当前位置:网站首页>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();
}
}
}
边栏推荐
- IO进程线程->进程->day4
- 力扣:第 304 场周赛
- High imitation [Huawei consumer business official website] and wonderful animation analysis: practice embedding JS code in low-code platform
- 下一个排列
- 如何建立私域流量?私域流量对企业有什么好处?
- (Note)阿克西斯ACASIS DT-3608双盘位硬盘阵列盒RAID设置
- 图扑软件数字孪生油气管道站,搭建油气运输管控平台
- 抓包工具Charles修改Response步骤
- QT web development - Notes - 3
- mysql 中 in 的用法
猜你喜欢
Biotin hydrazide HCl|CAS:66640-86-6|生物素-酰肼盐酸盐
C Language Basics_Union
Detailed explanation of calculation commands in shell (expr, (()), $[], let, bc )
cas:139504-50-0 美登素DM1|Mertansine|
CASA模型、CENTURY模型应用与案例分析
测试时大量TIME_WAIT
如何建立私域流量?私域流量对企业有什么好处?
etcd实现大规模服务治理应用实战
Biotin-EDA|CAS:111790-37-5| 乙二胺生物素
C语言基础_结构体
随机推荐
用C写小游戏(三子棋)
Button to control the running water light (timer)
PyCharm usage tutorial (detailed version - graphic and text combination)
What is the function of page directive contentPage/pageEncoding in JSP page?
Installation and use of pnpm
UVM信息服务机制
MySQL读写分离与主从延迟
AttributeError: module ‘clr‘ has no attribute ‘AddReference‘
Redisson实现分布式锁
UVM事务级建模
【论文阅读】Distilling the Knowledge in a Neural Network
unity pdg 设置隐藏不需要的节点以及实现自动勾选自动加载项
MySQL 中 count() 和 count(1) 有什么区别?哪个性能最好?
R语言plotly可视化:plotly可视化回归模型实际值和回归预测值的散点图分析回归模型的预测效能、一个好的模型大部分的散点在对角线附近(predicted vs actual)
tf.where使用
工程师如何对待开源 --- 一个老工程师的肺腑之言
科技云报道:实现元宇宙,英伟达从打造基础建设平台开始
Pycharm (1) the basic use of tutorial
mysql 中 in 的用法
R language plotly visualization: plotly visualizes the scatter plot of the actual value of the regression model and the predicted value of the regression, analyzes the prediction performance of the re