Skip to content

Commit 8ca5c6e

Browse files
committed
fix: correct rust solution
No.0904.Fruit Into Baskets
1 parent 9d43848 commit 8ca5c6e

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
1-
class Solution:
2-
def totalFruit(self, fruits: List[int]) -> int:
3-
cnt = Counter()
4-
j = 0
5-
for x in fruits:
6-
cnt[x] += 1
7-
if len(cnt) > 2:
8-
y = fruits[j]
9-
cnt[y] -= 1
10-
if cnt[y] == 0:
11-
cnt.pop(y)
12-
j += 1
13-
return len(fruits) - j
1+
use std::collections::HashMap;
2+
impl Solution {
3+
pub fn total_fruit(fruits: Vec<i32>) -> i32 {
4+
let n = fruits.len();
5+
let mut map = HashMap::new();
6+
let mut i = 0;
7+
for &fruit in fruits.iter() {
8+
*map.entry(fruit).or_insert(0) += 1;
9+
if map.len() > 2 {
10+
let k = fruits[i];
11+
map.insert(k, map[&k] - 1);
12+
if map[&k] == 0 {
13+
map.remove(&k);
14+
}
15+
i += 1;
16+
}
17+
}
18+
(n - i) as i32
19+
}
20+
}

0 commit comments

Comments
 (0)