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或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
强烈推荐
- 英国代购-畅购英伦
- 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