Problem
Solution
Analysis
Python implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class : def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ ans = 0 n = 0 for num in nums: if num == 1: n += 1 else: ans = max(n, ans) n = 0 return max(n, ans)
|
Java implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
class { public int findMaxConsecutiveOnes(int[] nums) { int ans = 0; int n = 0; for(int num : nums){ if(num == 1){ n ++; }else{ ans = ans > n ? ans : n; n = 0; } } return ans > n ? ans : n; } }
|
Time complexity
O(N).
Space complexity
O(1).
Links
485. Max Consecutive Ones
(中文版) 算法笔记: 力扣#485 最大连续1的个数
近期评论