字节跳动秋招面试原题:找零
LintCode 1503
找零
题目描述 某国的货币系统包含面值 1 元、4 元、16 元、64 元共 4 种硬币,以及面值 1024 元的纸币。 你现在使用 1024 元的纸币购买了一件价值为 N,0<N<=1024 元的商品,请问最少会收到多少个硬币作为找零。
题目描述
扫码免费做题 ↓↓↓
样例 1
样例输入1:
amount = 1014
样例输出1:
4
找零 2 个 4 元硬币,和 2 个 1 元硬币。
样例 2
样例输入2:
amount = 1004
样例输出2:
2
找零 1 个 16 元硬币,1 个 4 元硬币。
解题思路
我们可以算出要找的钱为1024−amount1024−amount,由于所有的硬币的面值两两成倍数关系,所以一定尽量每次优先用最大的面值去找零,如果最大的面值大于剩下的金额数,再用第二大的面值。利用贪心思想,从大到小进行计算。
代码思路
1. 令常量 VALUES=[64,16,4,1]VALUES=[64,16,4,1]。
2. 从大到小遍历,将 numbernumber 加上 change/valuechange/value,代表需要多少个面值 valuevalue 的硬币,changemodvaluechangemodvalue 代表用这种面值后剩下多少金额。
复杂度分析
时间复杂度:
· 只需常量次数的计算,时间复杂度为O(1)。
空间复杂度:
· 需要常量空间进行计算,空间复杂度为O(1)。
源代码
publicclassSolution {
/**
* @param amount: The amount you should pay.
* @return: Return the minimum number of coins for change.
*/
publicintgiveChange(int amount) {
final List<Integer> VALUES = new ArrayList<Integer>();
VALUES.add(64);
VALUES.add(16);
VALUES.add(4);
VALUES.add(1);
int change = 1024 - amount;
int number = 0;
for (int i = 0; i < 4; i++) {
intvalue = (int)VALUES.get(i);
number += change / value;
change %= value;
}
return number;
}
}
查看完整代码,向左滑动
点击【阅读原文】,查看领扣原题。
阅读原文 关键词
硬币
面值
常量
2个
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。