首页 > 代码库 > 485. Max Consecutive Ones

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: 3Explanation: 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

c代码:

 1 int findMaxConsecutiveOnes(int* nums, int numsSize) { 2     int count = 0, max = 0; 3     for(int i = 0; i < numsSize; i++){ 4         if(nums[i] == 1){ 5             count++; 6         } 7         else{ 8             if(count > max) 9                 max = count;10             count = 0;11         }12     }13     //如果最后一个是1,这个判断是很有必要的14     if(count > max)15         max = count;16     return max;17     18 }

c++:

 1 class Solution { 2 public: 3     int findMaxConsecutiveOnes(vector<int>& nums) { 4         int count = 0, maxn = 0; 5         int size = nums.size(); 6         for(int i = 0; i < size; i++){ 7             if(nums[i] == 1){ 8                 count++; 9             }10             else{11                 maxn = max(count, maxn);12                 count = 0;13             }14         }15         maxn = max(count, maxn);16         return maxn;17     }18 };

用向量做法:

 1 class Solution { 2 public: 3     int findMaxConsecutiveOnes(vector<int>& nums) { 4         vector<int> cnt(nums.size()); 5         cnt[0] = nums[0]; 6         int maxn = 0; 7         for(int i = 1; i < nums.size(); i++){ 8             if(nums[i] == 0){ 9                 cnt[i] = 0;10                 maxn = max(maxn, cnt[i-1]);11             } else {12                 cnt[i] = cnt[i-1] + 1;13             }14         }15         maxn = max(maxn, cnt[nums.size() - 1]);16         return maxn;17     }18 };

没有必要用c++的,用c,通过运行时间,显然c快

 

485. Max Consecutive Ones