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

LeetCode:485. Max Consecutive Ones

时间:2017-02-06 13:22:30      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:oid   log   last   int   ted   this   str   math   static   

 1 package Today;
 2 //LeetCode:485. Max Consecutive Ones
 3 /*
 4 Given a binary array, find the maximum number of consecutive 1s in this array.
 5 
 6 Example 1:
 7 Input: [1,1,0,1,1,1]
 8 Output: 3
 9 Explanation: The first two digits or the last three digits are consecutive 1s.
10     The maximum number of consecutive 1s is 3.
11 Note:
12 
13 The input array will only contain 0 and 1.
14 The length of input array is a positive integer and will not exceed 10,000
15  */
16 public class findMaxConsecutiveOnes485 {
17     public static int findMaxConsecutiveOnes(int[] nums) {
18         int max=0;
19         int count=0;
20         for(int i=0;i<nums.length;i++){
21             if(nums[i]==1){
22                 count++;
23             }else{
24                 if(count>max)
25                     max=count;
26                 count=0;
27             }
28             if(count>max)
29                 max=count;
30         
31         }
32         return max;
33     }
34     //study 思路很普通,人家写的好简约
35     public static int findMaxConsecutiveOnes2(int[] nums){
36         int maxhere=0,max=0;
37         for(int num:nums)
38             max=Math.max(max, maxhere=num==0?maxhere=0:maxhere+1);
39         return max;
40     }
41     public static void main(String[] args) {
42         // TODO Auto-generated method stub
43         int[] nums={1,1,0,1,1,1};
44         System.out.println(findMaxConsecutiveOnes(nums));
45         System.out.println(findMaxConsecutiveOnes2(nums));
46     }
47 
48 }

 

LeetCode:485. Max Consecutive Ones

标签:oid   log   last   int   ted   this   str   math   static   

原文地址:http://www.cnblogs.com/luluqiao/p/6369687.html

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