• 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

    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快

  • 相关阅读:
    mysql数据库存储的引擎和数据类型
    mysql数据库基本操作
    【转】linux yum命令详解
    [转]Linux rpm 命令参数使用详解
    【转】Linux GCC常用命令
    [转]linux下logrotate 配置和理解
    [转]Linux下chkconfig命令详解
    [转]linux之top命令
    [转]linux之ps命令
    互联网产品如何做到快与轻
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/6350073.html
Copyright © 2020-2023  润新知