leetcode 485. Max Consecutive Ones

485. Max Consecutive Ones 最大连续1的个数

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最多的位数

思路:遍历给定数组,把1连续出现的次数按照顺序存入一位数组,然后对一位数组进行排序,返回最大值。

困难:1.如何初始化不定大小的数组?或者可以用向量?

2.如何逆排序?

当前代码(有问题):

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) 
    {
        int i=0,j=0;
        string a[10000];                           //这样是否正确?最后的a.end()能取到a数组的最后一位吗?
        for(int i=0;i<nums.size();i++)
        {
        if(nums[i]==1)
            a[j]+=1;            
        else
            j+=1;                                 //遇到零则,把连续1的数量存入a数字的下一位
        }
        sort(a.begin(),a.end());                   //从小到大排序
        for(i=9999;i>=0;i--)                       // 不会逆序啊
        {
            if(a[i]!=0)
            return a[i]; 
        }
                                
    }
};

参考:

https://www.cnblogs.com/grandyang/p/6360942.html

这道题让我们求最大连续1的个数,不是一道难题。我们可以遍历一遍数组,用一个计数器cnt来统计1的个数,方法是如果当前数字为0,那么cnt重置为0,如果不是0,cnt自增1,然后每次更新结果res即可,参见代码如下:

解法1:

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int res = 0, cnt = 0;
        for (int num : nums) {               //for(x:y) x属于y,并且遍历y中所有元素。
            cnt = (num == 0) ? 0 : cnt + 1;
            res = max(res, cnt);
        }
        return res;
    }
};

解法2:

由于是个二进制数组,所以数组中的数字只能是0或1,那么连续1的和跟个数相等,所以我们可以计算和,通过加上num,再乘以num来计算,如果当前数字是0,那么sum就被重置为0,还是要更新结果res,参见代码如下:

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int res = 0, sum = 0;
        for (int num : nums) {
            sum = (sum + num) * num;
            res = max(res, sum);
        }
        return res;
    }
};

 

posted @ 2018-04-09 01:21  月夜_1  阅读(133)  评论(0编辑  收藏  举报