我们看一道比较简单的题,作为今天刷题的开胃菜。
柠檬水找零
LeetCode传送门860. Lemonade Change
题目
在柠檬水摊上,每一杯柠檬水的售价为 5 美元。顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。
每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。
注意,一开始你手头没有任何零钱。
给你一个整数数组 bills ,其中 bills[i] 是第 i 位顾客付的账。如果你能给每位顾客正确找零,返回 true ,否则返回 false 。
At a lemonade stand, each lemonade costs 5, 20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.
Note that you don't have any change in hand at first.
Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with correct change, or false otherwise.
Example:
Input: bills = [5,5,5,10,20]
Output: true
Explanation:
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change, we output true.
Input: bills = [5,5,10,10,20]
Output: false
Explanation:
From the first two customers in order, we collect two $5 bills.
For the next two customers in order, we collect a $10 bill and give back a $5 bill.
For the last customer, we can not give change of $15 back because we only have two $10 bills.
Since not every customer received correct change, the answer is false.
Input: bills = [5,5,10]
Output: true
Input: bills = [10,10]
Output: false
Constraints:
1 <= bills.length <= 105bills[i]is either5,10, or20.
思考线
解题思路
根据题意,我们可以记录下5美元和10美元的数量。
在找零的时候我们能找10美元就不用找5美元,直到结束或者发现不能找零为止。
根据上面的理解我们可以得到代码如下
/**
* @param {number[]} bills
* @return {boolean}
*/
var lemonadeChange = function (bills) {
// 记录 5, 10美元的数量,能找10美元不用5美元,直到结束,或者发现不能找零。
const hash = {
five: 0,
ten: 0,
}
for (let i = 0; i < bills.length; i++) {
const item = bills[i];
if (item === 5) {
hash.five++
} else if (item === 10) {
hash.ten++;
hash.five--;
if (hash.five < 0) return false;
} else {
if (hash.ten > 0) {
hash.ten--;
hash.five--;
} else {
hash.five -=3;
}
if (hash.five < 0 || hash.ten < 0) return false;
}
}
return true;
};
复杂度分析
- 时间复杂度:O(N),其中 N 是 bills 的长度。
- 空间复杂度:O(1)。