LeetCode 485:連續最大1的個數 Max Consecutive Ones(python java)

公衆號:愛寫bug

給定一個二進制數組, 計算其中最大連續1的個數。

Given a binary array, find the maximum number of consecutive 1s in this array.

示例 1:

輸入: [1,1,0,1,1,1]
輸出: 3
解釋: 開頭的兩位和最後的三位都是連續1,所以最大連續1的個數是 3.

注意:

  • 輸入的數組只包含 01
  • 輸入數組的長度是正整數,且不超過 10,000。

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

解題思路:

​ 記錄一個指針向右移動,用一個數記錄1的個數,遇1就累加1,遇0就倒置爲0。具體見 Java 註釋。

Java:

class Solution{
    public int findMaxConsecutiveOnes(int[] nums) {
        int temp=0,count=0;//temp記錄當前連續1的個數,count記錄當前最大連續1的個數
        for (int i=0;i<nums.length;i++){//指針右移
            if(nums[i]==1){
                temp++;//遇1累加1
            }else{
                if(count<temp){
                    count=temp;//記錄目前最大連續1的個數
                }
                temp=0;//遇0倒置爲0
            }
        }
        return (count>temp)? count:temp;//返回count、temp中較大的數
    }
}

注意:

​ 返回值必須是counttemp 中較大的一個。明明已經比較了counttemp,並把較大的賦值給count ,很明顯是count 更大,爲什麼還要比較?

​ 這是因爲還有一種輸入數組全爲1的情況,此時temp一直累加,從未遇到0,所以count自始至終都不可能得到temp的值。

python3:

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        count=temp=0
        for num in nums:
            if num==1:
                temp+=1
            else:
                if(count<temp):
                    count=temp
                temp=0
        return count if count>temp else temp
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章