小赖子的英国生活和资讯

C++ 编程练习题 – 最多连续的 1

阅读 桌面完整版

Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
Note: The input array will only contain 0 and 1.
The length of input array is a positive integer and will not exceed 10,000

learn-to-code C++ 编程练习题 - 最多连续的 1 ACM题解 程序设计

学编程

题意: 给定一个只含有1或0的数组, 求连续为1最长长度是多少.

两个变量, 记录当前遇到最长的长度m1, 还有从上一次遇到0以来最长1的长度r, 边遍历边更新. 遇到0就重置r.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        auto r = 0, m1 = 0;
        for (auto n: nums) {
            if (n == 1) {
                r ++;
                m1 = max(m1, r);
            } else {
                r = 0;
            }
        }
        return m1;
    }
};
class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        auto r = 0, m1 = 0;
        for (auto n: nums) {
            if (n == 1) {
                r ++;
                m1 = max(m1, r);
            } else {
                r = 0;
            }
        }
        return m1;
    }
};

PYTHON的另一种做法: 把数组连接成字符串, 然后按0重新分组, 求出剩下为1字符串的分组中最长的那个即可.

1
return max([len(i) for i in "".join(map(str, nums)).split('0')])
return max([len(i) for i in "".join(map(str, nums)).split('0')])

英文: Coding Exercise – Find Max Consecutive Ones

强烈推荐

微信公众号: 小赖子的英国生活和资讯 JustYYUK

阅读 桌面完整版
Exit mobile version