題目
先來看一下題目:
Given a binary array, find the maximum number of consecutive 1s in this >array.
The input array will only contain 0 and 1.
The length of input array is a positive integer and will not exceed 10,000
題目的翻譯是:給定一個二進制數組(也就是數組中隻有0和1兩種類型的元素),要求尋找數組中最大的連續的1的數目。
思路
好久沒有遇到這麼簡單的題目了,解這題的思路就是在周遊數組的同時維護兩個變量:一個是目前連續的1的數目,另一個是目前為止整個數組連續的1的最大數目,如果周遊的元素是1,則更新這兩個值,如果是0,則将目前連續的1的數目定為0;
好,廢話不多說,代碼如下,也挺簡潔的:
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int max=0,curr=0;
for(int iterator:nums){
if(iterator==0){
curr=0;
}else{
curr++;
if(curr>max)
max=curr;
}
}
return max;
}
}
複制
這個方法隻需周遊一遍數組,accept之後顯示runtime為9ms
更好的辦法
送出了之後發現一個runtime隻需7ms的解答,代碼如下:
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
if(nums == null || nums.length < 1) return 0;
int count = 0, temp = 0;
for(int i=0; i
複制
跟我的代碼不同之處在于我是當目前周遊的元素時1是比較max與temp的大小然後取較大的一個,它是當目前周遊的元素是0的時候才進行判斷,毫無疑問,這樣減少了判斷的次數,減少了時間開銷,是一個更優的解法,也難怪它的runtime才7ms,棒!