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

LeetCode 594: Longest Harmonious Subsequence

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

基本資料
#

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

  • 提交紀錄:Accepted ×2 → Runtime Error

解題思路
#

子序列不需要連續,所以順序不重要,只要計數(Hash Table 模板一)。和諧子序列只會包含 x 和 x + 1 兩種值,對每個 x,如果 x + 1 也存在,答案候選就是 cnt[x] + cnt[x + 1]。只看 x + 1 就夠了,x - 1 的情況會在處理 x - 1 時算到。

我的解法
#

class Solution:
    def findLHS(self, nums: List[int]) -> int:
        cnt = Counter(nums)
        return max((cnt[x] + cnt[x + 1] for x in cnt if x + 1 in cnt), default=0)

複雜度
#

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

要特別避免的錯誤
#

  • 只有一種值(例如全部相同)不算和諧,要回傳 0。

面試口說整理
#

子序列不用連續,所以我直接計數,對每個值 x,如果 x + 1 也存在,就用兩者次數相加更新答案。時間 O(n)。

相關文章

LeetCode 217: Contains Duplicate
·1 分鐘
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 解題筆記:轉成 set 後長度變短就代表有重複
LeetCode 219: Contains Duplicate II
·1 分鐘
LeetCode Easy Array Hash-Table Sliding-Window
LeetCode 219 解題筆記:雜湊表記錄每個值最後一次出現的位置,只需要跟最近的那次比距離
LeetCode 169: Majority Element
·1 分鐘
LeetCode Easy Array Hash-Table Divide-and-Conquer Sorting
LeetCode 169 解題筆記:Boyer-Moore 投票,不同的數兩兩抵消,最後留下的就是出現超過一半的那個
LeetCode 500: Keyboard Row
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 500 解題筆記:鍵盤的三列各做成集合,單字轉小寫後的字元集合是某一列的子集就保留
LeetCode 506: Relative Ranks
·1 分鐘
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 506 解題筆記:把 index 按分數由高到低排序,前三名給獎牌,其他給名次的字串,放回原本的位置
LeetCode 349: Intersection of Two Arrays
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 解題筆記:兩個陣列各轉成集合取交集