Problem: 128. 最长连续序列
思路
参考:
-
https://leetcode.cn/problems/longest-consecutive-sequence/solutions/276931/zui-chang-lian-xu-xu-lie-by-leetcode-solution/?envType=study-plan-v2&envId=top-100-liked
-
https://leetcode.cn/problems/longest-consecutive-sequence/solutions/2362995/javapython3cha-xi-biao-ding-wei-mei-ge-l-xk4c/?envType=study-plan-v2&envId=top-100-liked
解题方法
-
使用
set()
构建 hash table,并非总是依赖 dict,应该根据实际选取; -
set 天然的适合去重,这道题认识到去重是很重要的;
-
如何判断一个子序列首部?
num-1
不在 set 里! -
如何判断一个子序列尾部?
num+1
不在 set 里!
额外讨论(来自 GPT)
1 python中使用set()
构建hash table
In Python, a set
is implemented using a hash table. This is why sets have very efficient performance characteristics for certain operations, especially for checking membership, adding elements, and removing elements. Here’s a brief overview of how this works:
- Hash Table Mechanism:
-
A hash table is a data structure that uses a hash function to map values (keys) to positions in an array.
-
In the case of a Python set, the elements of the set are the keys in the underlying hash table.
- Efficient Operations:
-
Membership Testi