当前位置:网站首页>leetcode-6132: Make all elements in array equal to zero
leetcode-6132: Make all elements in array equal to zero
2022-08-01 07:58:00 【chrysanthemum bat】
leetcode-6132:Makes all elements in the array equal to zero
题目
给你一个非负整数数组 nums .在一步操作中,你必须:
pick a positive integer x ,x 需要小于或等于 nums 中 最小 的 非零 元素.
nums Subtract each positive integer in x.
返回使 nums All elements in are equal 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 Every element in is already 0 ,So no action is required.
解题
方法一:模拟
由于nums.length最大为100,So you can use brute force simulation to do this problem
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;
}
};
方法二:转化为 Find the number of non-zero and distinct elements
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();
}
};
边栏推荐
- 网络个各种协议
- 好的plm软件有哪些?plm软件排行榜
- VoLTE Basic Learning Series | Enterprise Voice Network Brief
- 最新的Cesium和Three的整合方法(附完整代码)
- 走进音视频的世界——mp3封装格式
- LeetCode240+312+394
- pytest接口自动化测试框架 | 使用函数返回值的形式传入参数值
- pytest interface automation testing framework | parametrize source code analysis
- XX市消防救援指挥中心实战指挥平台多链路聚合解决方案实例
- leetcode-6132:使数组中所有元素都等于零
猜你喜欢
随机推荐
Pod环境变量和initContainer
gethostbyname \ getaddrinfo 解析域名IP地址不安全的原因
2022.7.31-----leetcode.1161
特殊的日子,值得纪念
mysql查看cpu使用情况
Data Analysis 5
Shell执行SQL发邮件
并发编程13-JUC之CountDownLatch
基于百度OCR的网站验证码在线识别
XX市消防救援指挥中心实战指挥平台多链路聚合解决方案实例
leetcode-6132:使数组中所有元素都等于零
企业数据虚拟化综合指南
Go supports OOP: use struct instead of class
Self-made a remote control software - VeryControl
C语言中编译时出现警告C4013(C语言不加函数原型产生的潜在错误)
JSON 与 JS 对象的区别
HoloView -- Tabular Datasets
SaaS安全认证综合指南
升级为重量级锁,锁重入会导致锁释放?
Go 支持 OOP: 用 struct 代替 class