当前位置:网站首页>leetcode-6132:使数组中所有元素都等于零
leetcode-6132:使数组中所有元素都等于零
2022-08-01 07:50:00 【菊头蝙蝠】
leetcode-6132:使数组中所有元素都等于零
题目
给你一个非负整数数组 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 ,所以不需要执行任何操作。

解题
方法一:模拟
由于nums.length最大为100,因此可以使用暴力模拟来做这道题
class Solution {
public:
int minimumOperations(vector<int>& nums) {
int n=nums.size();
int res=0;
for(int i=0;i<n;i++){
sort(nums.begin(),nums.end());
if(nums[i]==0) continue;
for(int j=n-1;j>=i;j--){
nums[j]-=nums[i];
}
res++;
}
return res;
}
};
方法二:转化为 求非零且不同的元素个数
class Solution {
public:
int minimumOperations(vector<int>& nums) {
unordered_set<int> set;
for(int num:nums){
if(num!=0) set.insert(num);
}
return set.size();
}
};
边栏推荐
猜你喜欢
随机推荐
搜索框字符自动补全
VoLTE基础学习系列 | 什么是SIP和IMS中的Forking
pytest接口自动化测试框架 | parametrize叠加使用
zip package all files in the directory (including hidden files/folders)
拳头游戏免版权音乐下载,英雄联盟无版权音乐,可用于视频创作、直播
LeetCode240+312+394
JVM: Runtime Data Area - PC Register (Program Counter)
支付宝如何生成及配置公钥证书
图像基本操作的其他内容
my creative day
监听父元素宽高,自适应插件大小
巧妙利用unbuffer实时写入
pytest接口自动化测试框架 | parametrize中ids的用法
Fist game copyright-free music download, League of Legends copyright-free music, can be used for video creation, live broadcast
【HDLBits 刷题】Circuits(1)Combinational Logic
The socket option
类似 MS Project 的项目管理工具有哪些
flink sql-client,怎么处理源端与目标增加端,sql-client包括映射表与JOB如
C语言学习概览(三)
Monitor the width and height of the parent element, adapt to the size of the plug-in









