2018年2月4日 星期日

[LeetCode] 485. Max Consecutive Ones

轉自LeetCode

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
<Solution>

這題不難,直接照題意寫個O(n)的解法就會過

參考了一個解法,更加簡潔

主要想法就是,遇到0,重置 count 就行

code 如下

C++
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
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
}
}

沒有留言:

張貼留言