leetcode485. 最大连续 1 的个数

思路:【双指针】

left左边界,right往右跑遇到0,则计算该长度。并更新cnt(最大连续1个数)。

class Solution {
public:
    int findMaxConsecutiveOnes(vector& nums) {
        int left = 0, right = 0;
        int cnt = 0;
        while (left != nums.size()) {
            if (nums[left] == 0) {
                left++;
                continue;
            }
            right = left;
            while (right != nums.size()) {
                if (nums[right] == 0) {
                    int t = right - left;
                    if (t > cnt) {
                        cnt = t;
                    }
                    left = right;
                    break;
                }
                right++;
            }
            if (right == nums.size()) {
                int t = right - left;
                if (t > cnt) {
                    cnt = t;
                }
                break;
            }
        }
        return cnt;
    }
};

leetcode485. 最大连续 1 的个数_第1张图片

 

emmm怎么看答案一次遍历就可以完成呢?

leetcode485. 最大连续 1 的个数_第2张图片

思路:一次遍历

设置两个变量,cnt记录当前小区间的 1 的个数,然后maxcnt记录整个nums数组的 1 的个数(结束一个小区间,满足条件就更新一下)

代码

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

 Java 代码

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int cnt = 0, maxcnt = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] == 1){
                cnt++;
            }else{
                maxcnt = Math.max(cnt, maxcnt);
                cnt = 0;
            }
        }
        maxcnt = Math.max(cnt, maxcnt);
        return maxcnt;
    }
}

你可能感兴趣的:(LeetCode,算法,leetcode,数据结构)