leetcode/
max_consecutive_ones.rs

1//! # 485. 最大连续1的个数
2//!
3//! 难度 简单
4//!
5//! 给定一个二进制数组, 计算其中最大连续1的个数。
6//!
7//! ## 示例 1:
8//!
9//! ```text
10//! 输入: [1,1,0,1,1,1]
11//! 输出: 3
12//! 解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3。
13//! ```
14//!
15//! ## 注意:
16//!
17//! - 输入的数组只包含 0 和 1。
18//! - 输入数组的长度是正整数,且不超过 10,000。
19//!
20//! See [leetcode](https://leetcode-cn.com/problems/max-consecutive-ones/)
21
22pub struct Solution;
23
24impl Solution {
25    /// 使用 `Iterator` 会很简单
26    pub fn find_max_consecutive_ones(nums: Vec<i32>) -> i32 {
27        nums
28            .split(|&x| x == 0)
29            .map(|v| v.len())
30            .max()
31            // because split an empty vector will at least return an empty slice
32            // which makes sense, so `max()` will always return `Some(T)`.
33            // But the `max()` function signature returns `Option<T>`, we will use `unwrap_or(default)` for that.
34            .unwrap_or(0) as i32
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::Solution;
41
42    #[test]
43    fn test() {
44        let t = |n| Solution::find_max_consecutive_ones(n);
45        assert_eq!(3, t(vec![1, 1, 0, 1, 1, 1]));
46        assert_eq!(0, t(vec![0, 0, 0, 0]));
47        assert_eq!(0, t(vec![]));
48    }
49}