欢迎来到PJCK的博客

(双指针) 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;
    }
};

 

posted @ 2019-04-28 17:35  PJCK  阅读(148)  评论(0编辑  收藏  举报