当前位置:网站首页>c# LeetCode刷题笔记4-拿硬币
c# LeetCode刷题笔记4-拿硬币
2022-07-19 09:25:00 【雪墩墩】
c# LeetCode刷题笔记4-拿硬币
1.题目描述
桌上有 n 堆力扣币,每堆的数量保存在数组 coins 中。我们每次可以选择任意一堆,拿走其中的一枚或者两枚,求拿完所有力扣币的最少次数。
示例 1:
输入:[4,2,1]
输出:4
解释:第一堆力扣币最少需要拿 2 次,第二堆最少需要拿 1 次,第三堆最少需要拿 1 次,总共 4 次即可拿完。
示例 2:
输入:[2,3,10]
输出:8
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/na-ying-bi
2.解析:首先当然是遍历数组,判断数组中的值是不是小于等于2,如果是的话,那么一次就拿完了。如果大于2的话,那么先要判断%2是否为0,不为0的话,直接拿该数除以2,例如值为8,那么就需要8/2=4次可以拿完,如果%2不为0,那么需要该数/2的基础上再加1,就拿9举例,就是9/2+1=4+1=5。
3.代码:
public int MinCount(int[] coins)
{
int count = 0;
for (int i = 0; i < coins.Length; i++)
{
//如果硬币的个数小于等于2 那么只需要一次
if(coins[i]<=2)
{
count++;
}
//如果硬币的个数大于2
else
{
//先判断%2是否等于0,等于0的话count=coins[i] / 2;不等于0的话在coins[i] / 2的基础上加一。
if (coins[i]%2==0)
{
count += coins[i] / 2;
}
else
{
count += coins[i] / 2;
count += 1;
}
}
}
return count;
}
边栏推荐
猜你喜欢
Why psp22 is important to Polkadot ecosystem
QGIS开发插件的文件路径
C# 基于MessageBox类的消息对话框讲解
Discussion on segment tree · number of ordinary segments | number of multiplicative segments | chairman tree
Mysql 主从配置
一汽红旗“王炸”上市,安全、舒适一个不落
CDH之impala
OpenHarmony littlefs文件系统存储结构与IO性能优化分析
A large number of programmers were discouraged!
[untitled]
随机推荐
When flinkcdc synchronizes data from sqlserver to MySQL, the timestamp xdbmask is in sqlserver
STL vector容量
2022-07-18:以下go语言代码输出什么?A:Groutine;B:Main;C:Goroutine;D:GoroutineMain。 package m
oracle rac rman备份报错ora-19501 ora-15081
从工程师到技术leader思维升级
Shopify卖家:分享做社交媒体营销的几个技巧!
QIODevice
OpenHarmony littlefs文件系统存储结构与IO性能优化分析
[HDU 6095] Rikka with Competition
How to implement dynamic submission of SQL jobs and control of startup and shutdown?
在 IDEA 里下个五子棋不过分吧?
基于CoreData PencilKit如何使用 SwiftUI 创建绘图应用程序
Scratch judge leap year electronic society graphical programming scratch grade examination level 4 true question and answer analysis June 2022
SQL SERVER alwayson ,可以从从库做CDC么?
Degradation technology of template and generic programming
STL vector的输出
巴比特 | 元宇宙每日必读:虚拟人热度减退,有的“出道即巅峰”,围观人群都散了?...
JS method of obtaining URL address bar parameters to solve the problem of Chinese garbled code
Docker installs common software redis
構建工具