-
Notifications
You must be signed in to change notification settings - Fork 24
/
lib.rs
75 lines (71 loc) · 2.84 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
struct Solution {}
impl Solution {
// 理解起来应该很容易,但是时间复杂度有点大,可以用hashMap来优化查找时间,由于主要目的是为了熟悉Rust语法这里就沿用这个答案
pub fn lemonade_change(bills: Vec<i32>) -> bool {
let mut dp = vec![0; bills.len()];
let mut i = 0;
let mut res = true;
while i < bills.len() {
if bills[i] == 5 {
dp[i] = bills[i]
} else {
let mut temp = bills[i];
while temp != 5 {
let max = get_max(&mut dp, temp); // 找到dp数组中小于当前顾客给的金额的最大值
if max == 0 {
res = false;
break;
}
temp = temp - max; // 减去找到的金额大小,如果不满足5,则继续找,例如20-10-5=5
}
if res == false {
break;
}
dp[i] = bills[i];
}
i += 1;
}
res
}
}
fn get_max(dp: &mut Vec<i32>, current: i32) -> i32 {
let mut max = 0;
let mut index = 0;
let mut i = 0;
while i < dp.len() {
let val = dp[i];
if val > max && val < current {
max = val;
index = i;
}
i += 1;
}
dp[index] = 0; // 找到金额后置为0代表已经找零给顾客了
max
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tests() {
let coins: Vec<i32> = vec![
5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5,
20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5,
10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5,
20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5,
10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5,
20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5,
10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5,
20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5,
10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5,
20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5,
10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5,
20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5,
10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5,
20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5,
10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5, 20, 5, 10, 5,
20, 5, 10, 5, 20, 5, 10, 5, 20,
];
Solution::lemonade_change(coins);
}
}