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 and1 . - The length of input array is a positive integer and will not exceed 10,000
這題不難,直接照題意寫個O(n)的解法就會過
參考了一個解法,更加簡潔
主要想法就是,遇到0,重置 count 就行
code 如下
C++
code 如下
C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int findMaxConsecutiveOnes(vector<int>& nums) { | |
int ans = 0, cnt = 0; | |
for(const auto &n : nums) { | |
cnt = n == 0 ? 0 : cnt + 1; | |
ans = max(ans, cnt); | |
} | |
return ans; | |
} | |
}; |
kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun findMaxConsecutiveOnes(nums: IntArray): Int { | |
var count = 0 | |
var ans = 0 | |
for(n in nums) { | |
count = if(n == 0) 0 else count + 1 | |
ans = Math.max(ans, count) | |
} | |
return ans | |
} | |
} |
沒有留言:
張貼留言