LeetCode Solution, Easy, 485 Max Consecutive Ones

尋找最長的連續 1

485. Max Consecutive Ones

題目敘述

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

Example 1:

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:

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

Constraints:

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

Hint 1:

You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.

題目翻譯

給定一個參數 nums,裡面只包含 0 和 1。然後要找出其中最長連續 1 的長度。

解法解析

此題是簡單的方式,使用一個迴圈去紀錄連續的 1。每次比對到 1 的時候,計算到 count,然後跟 result 比對,然後寫回比較大的值到 result

程式範例

Python
class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        count = 0
        result = 0
        for num in nums:
            if num == 1:
                count += 1
                result = max(result, count)
            else:
                count = 0
        return result
JavaScript
/**
 * @param {number[]} nums
 * @return {number}
 */
var findMaxConsecutiveOnes = function (nums) {
    let result = 0;
    let count = 0;

    for (const num of nums) {
        if (num === 1) {
            count++;
            result = Math.max(result, count);
        } else {
            count = 0;
        }
    }
    return result;
};
Go
class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        count = 0
        result = 0
        for num in nums:
            if num == 1:
                count += 1
                result = max(result, count)
            else:
                count = 0
        return result
Swift
class Solution {
    func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {
        var result = 0
        var count = 0

        for num in nums {
            if num == 1 {
                count += 1
                result = max(result, count)
            } else {
                count = 0
            }
        }

        return result
    }
}
Kotlin
class Solution {
    fun findMaxConsecutiveOnes(nums: IntArray): Int {
        var result = 0
        var count = 0

        nums.forEach {
            when (it) {
                1 -> {
                    count++
                    result = Math.max(count, result)
                }
                else -> count = 0
            }
        }

        return result
    }
}

Did you find this article valuable?

Support 攻城獅 by becoming a sponsor. Any amount is appreciated!