内容简介:公众号:爱写bug给定一个二进制数组, 计算其中最大连续1的个数。Given a binary array, find the maximum number of consecutive 1s in this array.
公众号:爱写bug
给定一个二进制数组, 计算其中最大连续1的个数。
Given a binary array, find the maximum number of consecutive 1s in this array.
示例 1:
输入: [1,1,0,1,1,1] 输出: 3 解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
注意:
- 输入的数组只包含
0和1。 - 输入数组的长度是正整数,且不超过 10,000。
Note:
- The input array will only contain
0and1. - The length of input array is a positive integer and will not exceed 10,000
解题思路:
记录一个指针向右移动,用一个数记录1的个数,遇1就累加1,遇0就倒置为0。具体见 Java 注释。
Java:
class Solution{
public int findMaxConsecutiveOnes(int[] nums) {
int temp=0,count=0;//temp记录当前连续1的个数,count记录当前最大连续1的个数
for (int i=0;i<nums.length;i++){//指针右移
if(nums[i]==1){
temp++;//遇1累加1
}else{
if(count<temp){
count=temp;//记录目前最大连续1的个数
}
temp=0;//遇0倒置为0
}
}
return (count>temp)? count:temp;//返回count、temp中较大的数
}
}
注意:
返回值必须是 count 与 temp 中较大的一个。明明已经比较了 count 和 temp ,并把较大的赋值给 count ,很明显是 count 更大,为什么还要比较?
这是因为还有一种输入数组全为1的情况,此时temp一直累加,从未遇到0,所以count自始至终都不可能得到temp的值。
python3:
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
count=temp=0
for num in nums:
if num==1:
temp+=1
else:
if(count<temp):
count=temp
temp=0
return count if count>temp else temp
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- swoole之协程channel元素个数
- 用堆找出最小的 N 个数
- leetcode.69.求一个数的平方根
- 统计两个IP地址之间的IP个数
- 效率比较:几种方法判断一个数是否是素数
- C语言实现三个数从小到大排序/输出
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
深入理解Android内核设计思想(第2版 套装上下册)
林学森 / 人民邮电出版社 / 2017-7-1 / 158
全书从操作系统的基础知识入手,全面剖析进程/线程、内存管理、Binder机制、GUI显示系统、多媒体管理、输入系统、虚拟机等核心技术在Android中的实现原理。书中讲述的知识点大部分来源于工程项目研发,因而具有较强的实用性,希望可以让读者“知其然,更知其所以然”。本书分为编译篇、系统原理篇、应用原理篇、系统工具篇,共4篇25章,基本涵盖了参与Android开发所需具备的知识,并通过大量图片与实例......一起来看看 《深入理解Android内核设计思想(第2版 套装上下册)》 这本书的介绍吧!