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给定一个二进制数组,找出此数组中连续 1 的最大数量。
示例 1:
输入:[1,1,0,1,1,1]
输出:3
解释:前两位或后三位是连续的 1。
连续 1 的最大数量为 3。
注意:输入数组只包含 0 和 1。
输入数组的长度为正整数,且不超过 10,000
题意: 给定一个只含有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
C/C++编程
- C++ 编程练习题: 如何合并两个二叉树?
- C++ 编程练习题 - 找出第三大的数
- C++ 编程练习题 - 最多连续的 1
- C++ 编程练习题 - 左子树叶节点之和 (深度优先+广度优先+递归)
- C++ 编程练习题 - 最多水容器 (递归)
- C++的异步编程: std::future, std::async 和 std::promise
- C编程练习题: 翻转整数位
- C++编程练习题: 找出字符串的所有大小小组合
- C/C++ 中的内存管理器(堆与栈)
- C++编程练习题: 对两单向链表求和
强烈推荐
- 英国代购-畅购英伦
- TopCashBack 返现 (英国购物必备, 积少成多, 我2年来一共得了3000多英镑)
- Quidco 返现 (也是很不错的英国返现网站, 返现率高)
- 注册就送10美元, 免费使用2个月的 DigitalOcean 云主机(性价比超高, 每月只需5美元)
- 注册就送10美元, 免费使用4个月的 Vultr 云主机(性价比超高, 每月只需2.5美元)
- 注册就送10美元, 免费使用2个月的 阿里 云主机(性价比超高, 每月只需4.5美元)
- 注册就送20美元, 免费使用4个月的 Linode 云主机(性价比超高, 每月只需5美元) (折扣码: PodCastInit2022)
- PlusNet 英国光纤(超快, 超划算! 用户名 doctorlai)
- 刷了美国运通信用卡一年得到的积分 换了 485英镑
- 注册就送50英镑 – 英国最便宜最划算的电气提供商
- 能把比特币莱特币变现的银行卡! 不需要手续费就可以把虚拟货币法币兑换
微信公众号: 小赖子的英国生活和资讯 JustYYUK