首页 > 代码库 > LeetCode:485. Max Consecutive Ones
LeetCode:485. Max Consecutive Ones
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。