1375.二进制字符串前缀一致的次数
链接:1375.二进制字符串前缀一致的次数
难度:Medium
标签:数组
简介:返回二进制字符串在翻转过程中 前缀一致 的次数。
题解 1 - python
- 编辑时间:2023-06-14
- 执行用时:80ms
- 内存消耗:21.4MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def numTimesAllBlue(self, flips: List[int]) -> int:
        nmax = res = 0
        for i in range(len(flips)):
            nmax = max(nmax, flips[i])
            if nmax == i + 1: res += 1
        return res
题解 2 - cpp
- 编辑时间:2023-06-14
- 执行用时:40ms
- 内存消耗:37.6MB
- 编程语言:cpp
- 解法介绍:遍历,记录当前反转的最大值。
class Solution {
public:
    int numTimesAllBlue(vector<int>& flips) {
        int nmax = 0, res = 0;
        for (int i = 0; i < flips.size(); i++) {
            nmax = max(nmax, flips[i]);
            if (nmax == i + 1) res++;
        }
        return res;
    }
};
题解 3 - rust
- 编辑时间:2023-06-14
- 执行用时:4ms
- 内存消耗:2.3MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
    pub fn num_times_all_blue(flips: Vec<i32>) -> i32 {
        let (mut nmax, mut res) = (0, 0);
        for i in 0..flips.len() {
            nmax = nmax.max(flips[i]);
            if nmax as usize == i + 1 {
                res += 1
            }
        }
        res
    }
}