↓快轉到主要內容
  1. LeetCode/

LeetCode 485: Max Consecutive Ones

·1 分鐘· ·
LeetCode Easy Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-24

  • 提交紀錄:Accepted ×4

解題思路
#

跟 LC 674 一樣是走過連續段(Array 模板一):遇到 1 就加一,遇到 0 歸零,每一步更新最大值。

我的解法
#

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        best = cur = 0
        for x in nums:
            cur = cur + 1 if x == 1 else 0
            best = max(best, cur)
        return best

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 每一步都更新最大值,最後一段才不會漏掉。

面試口說整理
#

我掃一次,遇到 1 就把長度加一、遇到 0 就歸零,每一步都更新最大值。時間 O(n)、空間 O(1)。

相關文章

LeetCode 349: Intersection of Two Arrays
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 解題筆記:兩個陣列各轉成集合取交集
LeetCode 350: Intersection of Two Arrays II
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 解題筆記:保留重複次數的交集,Counter 相交(&)取兩邊次數的較小值
LeetCode 118: Pascal's Triangle
·1 分鐘
LeetCode Easy Array Dynamic-Programming
LeetCode 118 解題筆記:每一列頭尾是 1,中間每一格是上一列左上和正上方的和
LeetCode 136: Single Number
·1 分鐘
LeetCode Easy Array Bit-Manipulation
LeetCode 136 解題筆記:x ^ x = 0、x ^ 0 = x,把所有數 XOR 起來,出現兩次的互相抵消,剩下的就是答案
LeetCode 414: Third Maximum Number
·1 分鐘
LeetCode Easy Array Sorting
LeetCode 414 解題筆記:記錄三個不同的最大值,重複的數跳過;不到三個不同的數就回傳最大值
LeetCode 448: Find All Numbers Disappeared in an Array
·1 分鐘
LeetCode Easy Array Hash-Table
LeetCode 448 解題筆記:把陣列本身當雜湊表,看到 x 就把 nums[x - 1] 標成負數,最後還是正數的位置就是沒出現的數