We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 9d43848 commit 8ca5c6eCopy full SHA for 8ca5c6e
solution/0900-0999/0904.Fruit Into Baskets/Solution.rs
@@ -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
+use std::collections::HashMap;
+impl Solution {
+ pub fn total_fruit(fruits: Vec<i32>) -> i32 {
+ let n = fruits.len();
+ let mut map = HashMap::new();
+ let mut i = 0;
+ for &fruit in fruits.iter() {
+ *map.entry(fruit).or_insert(0) += 1;
+ if map.len() > 2 {
+ let k = fruits[i];
+ map.insert(k, map[&k] - 1);
+ if map[&k] == 0 {
+ map.remove(&k);
14
+ }
15
+ i += 1;
16
17
18
+ (n - i) as i32
19
20
+}
0 commit comments