当前位置:网站首页>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();
}
};
边栏推荐
猜你喜欢
第02章 MySQL的数据目录【1.MySQL架构篇】【MySQL高级】
XX市消防救援指挥中心实战指挥平台多链路聚合解决方案实例
最新的Cesium和Three的整合方法(附完整代码)
HoloView -- Tabular Datasets
Json对象和Json字符串的区别
22牛客多校1 C.Grab the Seat (几何 + 暴力)
七夕来袭——属于程序员的浪漫
【HDLBits 刷题】Circuits(1)Combinational Logic
Chapter 9 of Huawei Deep Learning Course - Convolutional Neural Network and Case Practice
图片无损压缩软件哪个好用:试试完全免费的JPG-C 图片批量修整压缩减肥工具吧 | 最新jpg批量修整工具下载
随机推荐
LeetCode240+312+394
pytest接口自动化测试框架 | parametrize源码解析
pytest接口自动化测试框架 | parametrize中ids的用法
VSCode 快捷键及通用插件推荐
配置我的kitty
pytest接口自动化测试框架 | 跳过模块
微信小程序请求封装
案例实践 --- Resnet经典卷积神经网络(Mindspore)
Monitor the width and height of the parent element, adapt to the size of the plug-in
华为深度学习课程第六、七章
SaaS安全认证综合指南
Json对象和Json字符串的区别
POJ1287联网题解
将aof文件转换为命令waoffle安装和使用
How to use Photoshop to composite star trail photos, post-processing method of night sky star trail photos
VoLTE基础学习系列 | 企业语音网简述
pytest interface automation testing framework | single/multiple parameters
Three aspects of Ali: How to solve the problem of MQ message loss, duplication and backlog?
最新的Cesium和Three的整合方法(附完整代码)
自制一款远程控制软件——VeryControl