首页 > 学院 > 开发设计 > 正文

leetcode485

2019-11-06 08:21:19
字体:
来源:转载
供稿:网友

1、Max Consecutive Ones 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

这个题直观看上去的思路就是,从头到尾遍历,设一个变量存最大值,设一个临时变量设当前值,对比当前和最大,交换or not,遇到0就更新临时变量为0就好了。

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

不过仔细一想,数组的数比较特殊,只有0和1,可借助乘0可以达到归零的效果,+1可以达到计数的作用。

class Solution {public: int findMaxConsecutiveOnes(vector<int> nums) { int max = 0; int sum = 0; for (int i=0; i<nums.size(); i++) { sum = (sum+nums[i])*nums[i]; if(max<sum){max=sum;} } return max; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表