• 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快

  • 相关阅读:
    F#学习开篇(一)
    F#学习(二)
    认识“闭包”
    Silverlight显示控件换行的几种方式
    关于P问题、NP问题、NPC问题
    LINQ&EF任我行(二)LinQ to Object
    WPF中资源的引用方法
    Linq to EF 与Linq to Object 使用心得
    C#中如何用拼音模糊匹配汉字的首字母
    WPF获取应用程序路径方法,获取程序运行路径方法
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/6350073.html
Copyright © 2020-2023  润新知