Max Consecutive Ones

原题: https://leetcode.com/problems/max-consecutive-ones/description/
题意: 给定一个二进制数组,计算数组中出现的最大连续1的个数
约定:(1)输入数组只包含0和1;(2)数组长度是正整数并且不会超过10000。
例子: 
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.
标签: consecutive、digits、1s、数组、max、面试
猜你感兴趣的圈子:
LeetCode交流圈
  • SLPH
    2017-08-11 08:57:50 1楼#1层
    一趟遍历+计数器:
    class Solution(object):
        def findMaxConsecutiveOnes(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            ans = cnt = 0
            for n in nums:
                if n == 1:
                    cnt += 1
                    ans = max(ans, cnt)
                else:
                    cnt = 0
            return ans
  • SLPH
    2017-08-11 08:59:31 2楼#1层
    由于是个二进制数组,所以数组中的数字只能是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;
        }
    };
  • SLPH
    2017-08-11 09:00:15 3楼#1层
    向量法:
    class Solution {
    public:
        int findMaxConsecutiveOnes(vector<int>& nums) {
            vector<int> cnt(nums.size());
            cnt[0] = nums[0];
            int maxn = 0;
            for(int i = 1; i < nums.size(); i++){
                if(nums[i] == 0){
                    cnt[i] = 0;
                    maxn = max(maxn, cnt[i-1]);
                } else {
                    cnt[i] = cnt[i-1] + 1;
                }
            }
            maxn = max(maxn, cnt[nums.size() - 1]);
            return maxn;
        }
    };
  • 回复
隐藏