[Leetcode]485. Max Consecutive Ones
求出連續相連幾個數字1
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
Think:
- 宣告一個記數、暫存
- 計算如果遇到1就加一,反之是0 就歸零
- 當num[i]==0 時,判斷 記數是否大於暫存 ,是 則將 記數值存入暫存
JAVA
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int tem = 0;
for(int i = 0; i<nums.length;i++){
if(nums[i]==1){
count++;
}
else{
if(count>=tem){
tem=count;
}
count=0;
}
}
if(count>=tem){
tem=count;
}
return tem;
}
}
留言
張貼留言