485. Max Consecutive Ones【easy】

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

解法一:

 class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int max = ;
int temp = ; for (int i = ; i < nums.size(); ++i)
{
if (nums[i] == )
{
temp++;
max = temp > max ? temp : max;
}
else
{
temp = ;
}
} return max;
}
};

思路很简单:是1就累加并且判断是否需要更新max,不是1就把累加和归为0,继续遍历。

 

解法二:

 public int findMaxConsecutiveOnes(int[] nums) {
int maxHere = , max = ;
for (int n : nums)
max = Math.max(max, maxHere = n == ? : maxHere + );
return max;
}

大神解释如下:

The idea is to reset maxHere to 0 if we see 0, otherwise increase maxHere by 1
The max of all maxHere is the solution

110111
^ maxHere = 1 110111
.^ maxHere = 2 110111
..^ maxHere = 0 110111
...^ maxHere = 1 110111
....^ maxHere = 2 110111
.....^ maxHere = 3

解法三:

 int findMaxConsecutiveOnes(int* nums, int numsSize) {
int max = ;
int sum = ;
for (int i=; i<numsSize; i++)
{
sum = (sum+nums[i])*nums[i];
if(max<sum){max=sum;}
}
return max;
}

这方法更牛逼,大神解释如下:Use the fact that multiplication with 0 resets everything..

最新文章

  1. 括号配对问题_栈&lt;stack&gt;
  2. Qt 自定义 滚动条 样式
  3. cornerstone的简单使用
  4. 1497: [NOI2006]最大获利 - BZOJ
  5. Ejabberd源码解析前奏--集群
  6. mongodb系列之--分片的原理与配置
  7. Netty基础系列(1) --linux网路I/O模型
  8. Python的re模块
  9. net core体系-web应用程序-4asp.net core2.0 项目实战(任务管理系统)-2项目搭建
  10. ng-packagr 打包报错 Public property X of exported class has or is using name &#39;Observable&#39; from external module “/rxjs/internal/Observable” but cannot be named
  11. MVC实战之排球计分(七)——软件的具体实现与测试
  12. 205. jetcache:你需要知道的小技巧
  13. python闭包和延迟绑定
  14. 人脸识别准备 -- 基于raspberry pi 3b + movidius
  15. Java设计模式学习记录-命令模式
  16. NodeJS笔记(一)-免安装设置
  17. request 的下载文件
  18. 2018.11.06 bzoj1097: [POI2007]旅游景点atr(最短路+状压dp)
  19. Mysql tinyint长度为1时在java中被转化成boolean型
  20. opencv(2)绘图

热门文章

  1. [BZOJ 1293] 生日礼物
  2. 【函数式权值分块】【分块】bzoj1901 Zju2112 Dynamic Rankings
  3. 通过python的logging模块输出日志文件
  4. Java高级架构师(一)第09节课:搭建基础的开发环境
  5. 关于Block Formatting Context--BFC和IE的hasLayout(转)
  6. 安装scrapy报错问题解决
  7. [Lync]lync同步通讯簿
  8. Asp.Net生命周期和Http管道技术
  9. u-boot修改出错的问题
  10. Laravel 5 系列教程三:视图变量传递和Blade