← 中文资源

简体中文版本

一次遍历求最长连续 1

单次循环同时维护当前连续 1 的长度与历史最大值两个字段:遇到 1 就延长当前段并刷新最优值,遇到 0 立即清零重新开一段。

阅读英文原文

实现说明

底层就是函数 max_consecutive_ones、main。 for &bit in nums 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • 运行整个文件:main 会依次驱动 max_consecutive_ones。

常见问题

「一次遍历求最长连续 1」这个示例怎么运行?

运行这个文件就行;脚本没有任何外部要求。

入口签名:fn max_consecutive_ones(nums: &[u8]) -> usize

核心语句

let (mut run, mut best) = (0usize, 0usize);

代码示例

fn max_consecutive_ones(nums: &[u8]) -> usize {
    // Single pass: track the current run length and the best run so far
    let (mut run, mut best) = (0usize, 0usize);
    for &bit in nums {
        if bit == 1 {
            run += 1;
            if run > best {
                best = run;
            }
        } else {
            run = 0;
        }
    }
    best
}

fn main() {
    println!("{}", max_consecutive_ones(&[1, 1, 0, 1, 1, 1]));
    println!("{}", max_consecutive_ones(&[1, 0, 1, 1, 0, 1]));
    println!("{}", max_consecutive_ones(&[0, 0, 0]));
}