当前位置:网站首页>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 <= 1000 <= 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();
}
}
}
边栏推荐
- 【开源项目】X-TRACK源码分析
- C Language Basics_Union
- Biotin-LC-Hydrazide|CAS:109276-34-8|生物素-LC-酰肼
- 工程师如何对待开源 --- 一个老工程师的肺腑之言
- PyCharm usage tutorial (more detailed, picture + text)
- etcd implements large-scale service governance application combat
- R语言plotly可视化:plotly可视化回归模型实际值和回归预测值的散点图分析回归模型的预测效能、一个好的模型大部分的散点在对角线附近(predicted vs actual)
- 王学岗-编译出运行的文件
- day_05_pickel 和 json
- Database triggers and transactions
猜你喜欢
随机推荐
Codeforces Round #811 (Div. 3)无DF
Axial Turbine Privacy Policy
Biotin hydrazide HCl|CAS:66640-86-6|生物素-酰肼盐酸盐
postman使用方法
Redis分布式锁
Biotin-EDA|CAS:111790-37-5| Ethylenediamine biotin
Database triggers and transactions
The packet capture tool Charles modifies the Response step
OneNote 教程,如何在 OneNote 中创建更多空间?
A little bit of knowledge - why do not usually cook with copper pots
JSP页面中page指令有哪些属性及方法可使用呢?
Write a small game in C (three chess)
类和对象【下】
下一个排列
王学岗-编译出运行的文件
UVM事务级建模
pnpm: Introduction
C语言基础_结构体
What is NoSQL?Databases for the cloud-scale future
next permutation

![Three types of [OC learning notes] Block](/img/40/edf59e6e68891ea7c9ab0481fe7bfc.png)







