zoukankan      html  css  js  c++  java
  • (双指针) leetcode 485. 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

    --------------------------------------------------------------------------------------------------------------------------------------

    这个题可以用双指针,时间复杂度是O(n),空间复杂度是O(1)。建立一个快指针和慢指针。

    C++代码1:

    class Solution {
    public:
        int findMaxConsecutiveOnes(vector<int>& nums) {
            if(nums.size() == 0)
                return 0;
            int maxSum = 0;
            int sum = 0;
            for(int i = 0; i < nums.size(); i++){
                if(nums[i] == 1){
                    sum++;
                }
                else{
                    maxSum = max(sum,maxSum);
                    sum = 0;
                }
            }
            //这个不能漏掉
            if(sum > maxSum)
                maxSum = sum;
            return maxSum;
        }
    };    

    C++代码2:

    class Solution {
    public:
        int findMaxConsecutiveOnes(vector<int>& nums) {
            if(nums.size() == 0)
                return 0;
            int maxSum = 0;
            int sum = 0;
            for(int i = 0; i < nums.size(); i++){
                if(nums[i] == 1){
                    sum++;
                }
                else{
                    sum = 0;
                }
                maxSum = max(sum,maxSum);
            }
            return maxSum;
        }
    };
  • 相关阅读:
    [hdu4631 Sad Love Story]最近点对,枚举
    [hdu4629 Burning]三角形面积并,扫描线
    [hdu4628 Pieces]二进制子状态,DP
    [hdu4627 The Unsolvable Problem]数论
    [hdu4622 Reincarnation]后缀数组
    [hdu5379 Mahjong tree]dfs计数
    [hdu5375 Gray code]DP
    决策树
    算法题解之位运算
    算法题解之滑动窗口
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10785360.html
Copyright © 2011-2022 走看看