One loop fast C++ Solution


  • 0

    Run Time: 36 ms, easy to understand.

    class Solution {
    public:
        int findMaxConsecutiveOnes(vector<int>& nums) {
            if (0 == nums.size()) {
                return 0;
            }
    
            vector<int> vecOneOff;
            int bStart = false;
            int maxOff = 0;
            int count = 0;
            for (int i = 0; i < nums.size(); ++i) {
                if (1 == nums[i]) {
                    bStart = true; // start to count 1
                }
    
                if (bStart && 1 == nums[i]) {
                    count++;
                }
                else {
                    if (bStart && 0 == nums[i]) {
                        if (count > maxOff) {
                            maxOff = count;
                        }
                    }
                    count = 0;
                    bStart = false;
                }
            }
    
            // If there is no '0' follow by the previous '1'  list
            if (count > maxOff) {
                maxOff = count;
            }
            return maxOff;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.