当前位置:网站首页>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();
}
};
边栏推荐
猜你喜欢
随机推荐
Json对象和Json字符串的区别
How to generate and configure public key certificate in Alipay
flink sql-client,怎么处理源端与目标增加端,sql-client包括映射表与JOB如
pytest接口自动化测试框架 | 执行失败跳转pdb
nodetype中值1、2、3分别代表什么意思
升级为重量级锁,锁重入会导致锁释放?
VoLTE基础学习系列 | 企业语音网简述
pytest interface automation testing framework | skip test classes
JVM:运行时数据区-PC寄存器(程序计数器)
I have three degrees, and I have five faces. I was "confessed" by the interviewer, and I got an offer of 33*15.
Data Analysis 5
The use of Golang: go template engine
【南瓜书ML】(task4)神经网络中的数学推导(更新ing)
Generate pictures based on the content of the specified area and share them with a summary
监听父元素宽高,自适应插件大小
JVM内存模型之深究模型特征
Pytest | skip module interface test automation framework
特殊的日子,值得纪念
VoLTE基础学习系列 | 什么是SIP和IMS中的Forking
小程序通过云函数操作数据库【使用get取数据库】









