当前位置:网站首页>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();
}
};
边栏推荐
- pytest interface automation testing framework | single/multiple parameters
- C语言学习概览(三)
- pytest接口自动化测试框架 | 跳过模块
- 179. 最大数
- Flink SQL - client, how to deal with the source side and to increase the target, the SQL - client including mapping table and the JOB such as
- 如何使用Photoshop合成星轨照片,夜空星轨照片后期处理方法
- JVM: Runtime Data Area - PC Register (Program Counter)
- Case practice --- Resnet classic convolutional neural network (Mindspore)
- Golang: go to connect and use mysql
- 图像基本操作的其他内容
猜你喜欢

Fist game copyright-free music download, League of Legends copyright-free music, can be used for video creation, live broadcast

rhcsa 第三次

支付宝如何生成及配置公钥证书

如何使用Photoshop合成星轨照片,夜空星轨照片后期处理方法

VSCode 快捷键及通用插件推荐

LabVIEW中局部变量和全局变量的分配

C语言中编译时出现警告C4013(C语言不加函数原型产生的潜在错误)

SaaS安全认证综合指南

The use of Golang: go template engine

Golang:go开启web服务
随机推荐
Self-made a remote control software - VeryControl
LevelSequence源码分析
centos 安装php7.4,搭建hyperf,转发RDS
套接字选项
Vim扩展内容
如何使用Photoshop合成星轨照片,夜空星轨照片后期处理方法
Electromagnetic compatibility introductory tutorial (6) test project
Data Analysis 6
案例实践 --- Resnet经典卷积神经网络(Mindspore)
zip打包目录所有文件(含隐藏文件/夹)
HoloView -- Tabular Datasets
LeetCode240+312+394
JVM: Runtime Data Area - PC Register (Program Counter)
【ASWC Arxml结构分解】-7-Explicit(显式)和Implicit(隐式) Sender-Receiver communication描述差异
LabVIEW中局部变量和全局变量的分配
【一句话攻略】彻底理解JS中的回调(Callback)函数
pytest接口自动化测试框架 | 执行失败跳转pdb
Centos install php7.4, build hyperf, forward RDS
22 Niu Ke Duo School 1 I. Chiitoitsu (Probability dp)
22 Grab the Seat 1 C.Grab the Seat (Geometry + Violence)