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

GD Star Rating
loading...
本文一共 115 个汉字, 你数一下对不对.
C++ 编程练习题 – 最多连续的 1. (AMP 移动加速版本)
上一篇: C++ 编程练习题 - 左子树叶节点之和 (深度优先+广度优先+递归)
下一篇: 试用 Linkedin (领英) 高级帐号 (Premium)

扫描二维码,分享本文到微信朋友圈
2d54b831757470c4a4ff03b2488c66d6 C++ 编程练习题 - 最多连续的 1 ACM题解 程序设计

评论