[LeetCode] 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的個數,不是一道難題。我們可以遍歷一遍數組,用一個計數器cnt來統計1的個數,方法是如果當前數字為0,那么cnt重置為0,如果不是0,cnt自增1,然后每次更新結果res即可,參見代碼如下:

 

解法一:

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

 

由於是個二進制數組,所以數組中的數字只能是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;
    }
};

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM