问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3714 访问。

给定一个二进制数组, 计算其中最大连续1的个数。

输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.

注意:

输入的数组只包含 0 和1。

输入数组的长度是正整数,且不超过 10,000。


Given a binary array, find the maximum number of consecutive 1s in this array.

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


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3714 访问。

public class Program {

    public static void Main(string[] args) {
int[] nums = null; nums = new int[] { 1, 1, 0, 1, 1, 1 };
var res = FindMaxConsecutiveOnes(nums);
Console.WriteLine(res); res = FindMaxConsecutiveOnes2(nums);
Console.WriteLine(res); Console.ReadKey();
} private static int FindMaxConsecutiveOnes(int[] nums) {
int count = 0;
int max = 0;
for(int i = 0; i < nums.Length; i++) {
if(nums[i] == 0) {
if(count > max) max = count;
count = 0;
} else {
count++;
}
}
return count > max ? count : max;
} private static int FindMaxConsecutiveOnes2(int[] nums) {
//同FindMaxConsecutiveOnes,只是写法稍微好看一点
int max = 0;
for(int i = 0, count = 0; i < nums.Length; i++) {
count = nums[i] == 1 ? count + 1 : 0;
max = count > max ? count : max;
}
return max;
} }

以上给出2种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3714 访问。

3
3

分析:

显而易见,以上2种算法的时间复杂度均为:  。

最新文章

  1. Remove Duplicates from Sorted Array II [LeetCode]
  2. urldecode解码方法
  3. Turtlebot入门篇
  4. leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal ----- java
  5. cxf2.7.10与Spring3.0.5集成时报错如下
  6. windbg命令学习4
  7. 美化 input type=file控件
  8. Java NIO--初步认识
  9. BZOJ 3685: 普通van Emde Boas树( 线段树 )
  10. Python round() 函数
  11. ES6 Promise 对象
  12. 关于Data URLs svg图片显示出错和浏览器URL hash #
  13. DevExpress v18.2新版亮点——DevExtreme篇(四)
  14. 51nod1986 Jason曾不想做的数论题
  15. Delphi ClientDataSet复制记录
  16. python 中numpy中函数hstack用法和作用
  17. Oracel 中的分页
  18. 00013 - top命令详解
  19. 服务器使用VMware系软件管理主机集群
  20. EntityFrameWork 图解

热门文章

  1. Python Ethical Hacking - TROJANS Analysis(3)
  2. Go的100天之旅-07条件和循环
  3. python-多任务编程02-进程(processing)
  4. vue中使用触摸事件,上滑,下滑,等
  5. ‘100%’wuxiao
  6. Fortify Audit Workbench 笔记 Path Manipulation
  7. ROS 机器人技术 - 广播与接收 TF 坐标
  8. 一分钟玩转 Spring IoC
  9. Python while 循环中使用 else 语句
  10. Entry基本用法