485. Max Consecutive Ones (連續出現最多次數的1)

題目

Given a binary array nums, return the maximum number of consecutive 1’s in the array.

返回陣列中連續出現最多次數的1


Example 1

1
2
3
Input: nums = [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.

Example 2

1
2
Input: nums = [1,0,1,1,0,1]
Output: 2

Constraints:

  • 1 <= nums.length <= 105
  • nums[i] is either 0 or 1.

我的解題

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int tmpNum = 0; //暫存數
int maxNum = 0; //最大數
for(int i=0;i<nums.length;i++){
if(nums[i] == 1){
tmpNum++; //若nums[i]的值==1,則暫存數+1
maxNum = Math.max(tmpNum,maxNum); //比較兩值並將較大的存進"最大數"
}else{
tmpNum = 0; //若nums[i]的值!=1,則暫存數=0
}
}
return maxNum; //回傳最大數
}
}