码迷,mamicode.com
首页 > 其他好文 > 详细

485. Max Consecutive Ones

时间:2017-01-25 22:12:51      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:out   color   imu   blog   ons   first   ret   nes   man   

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快

 

485. Max Consecutive Ones

标签:out   color   imu   blog   ons   first   ret   nes   man   

原文地址:http://www.cnblogs.com/qinduanyinghua/p/6350073.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!