(双指针) leetcode 485. Max Consecutive Ones

mac2022-06-30  97

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; } };

 

转载于:https://www.cnblogs.com/Weixu-Liu/p/10785360.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)