LeetCode 485. Max Consecutive Ones

Description

Given a binary array, find the maximum number of consecutive 1s in this array.

Example:

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

Analysis

解法一:循環查找連續全1子序列,以全1子序列的首尾座標的差(程序中是以全0子序列的首-全1子序列的首得到的)中的最大值作爲結果。
解法二:思路類似,全1子序列的元素的和就是長度,故直接不斷循環求和比較即可。
解法三:思路同解法二,區別在於利用a * 1 = aa * 0 = 0這樣的特點,用乘法代替了if分支,循環體行數減少。

Code

Version 1

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int i = 0, result = 0, temp = 0;
        while (i < nums.size()){
            while (nums[i] == 0 && i < nums.size()) i++;
            temp = i;
            while (nums[i] == 1) i++;
            result = max(result, i - temp);
        }
        return result;
    }
};

Version 2

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int result = 0, temp = 0;
        for (int i = 0; i < nums.size(); i++){
            if (nums[i] == 1){
                temp++;
                result = max(result, temp);
            }
            else temp = 0;
        }
        return result;
    }
};

Version 3

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int result = 0, temp = 0;
        for (int i = 0; i < nums.size(); i++){
            temp = (temp + nums[i]) * nums[i];
            result = max(result, temp);
        }
        return result;
    }
};

Appendix

I ran Version 2 three times and got three different results…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章