485. Max Consecutive Ones(python+cpp)

题目:

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的最长的长度,用0的index做。
把0出现的index记下来,在最开始分别补上-1 和len ,该列表每一位相减得到一个新的list,这个list的最大值-1就是答案。
python代码:

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        zero_index=[]
        for i ,n in enumerate(nums):
            if n==0:
                zero_index.append(i)
        result_list=[]
        zero_index.insert(0,-1)
        zero_index.append(len(nums))
        final_result=[]
        for i in range(len(zero_index)-1):
            final_result.append(zero_index[i+1]-zero_index[i]-1)
        return max(final_result)        

c++代码:

#include <vector>
#include <algorithm>
class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        
        vector<int> zero_index;
        for (int i=0;i<nums.size();i++)
        {
            if (nums[i]==0)
                zero_index.push_back(i);
        }
        zero_index.insert(zero_index.begin(),-1);
        zero_index.push_back(nums.size());
        vector<int> result;
        for(int i=0;i<zero_index.size()-1;i++)
        {
            result.push_back(zero_index[i+1]-zero_index[i]-1);
        }
        return *max_element(result.begin(),result.end());  
    }
};

但是这种做法实际上很慢,其实只要用一个变量记住最长的长度即可,这样只需要遍历一遍。
python代码:

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        _max=0
        tmp=0
        for num in nums:
            if num==1:
                tmp+=1
            else: 
                _max=max(_max,tmp)
                tmp=0
        _max=max(_max,tmp)
        return _max

注意最后还需要判断一下,否则答案不正确,因为else有可能根本没有进去。
c++代码:

#include <algorithm>
class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        
        int _max=0;
        int tmp=0;
        for(auto num:nums)
        {
            if (num==1)
                tmp++;
            else
            {
                _max=max(_max,tmp);
                tmp=0;
            }
        }
        _max=max(_max,tmp);
        return _max;   
    }
};

总结:
还是记住第二种方法吧,这种方法好像经常遇到唉,注意 tmp的归零哦。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值