文章目录
- 题目描述
- 题解思路
- 题解代码
- 题解链接
题目描述
题解思路
首先我们可以将所有数字保存在集合中,然后 最长连续序列的开头数字 - 1 一定不存在于数组中,想到这一点,这题就迎刃而解了
我们只需要遍历集合
如果遍历到的当前数字 - 1存在于数组中就跳过这个数字的处理
如果遍历到的当前数字 - 1不存在于数组中,找寻以当前数字开头的最长连续序列,然后与结果取最长值
最终遍历结果,返回最长的连续序列长度即可
题解代码
func longestConsecutive(nums []int) int {m := map[int]struct{}{}for i := 0; i < len(nums); i++ {m[nums[i]] = struct{}{}}ans := 0for num := range m {if _, ok := m[num - 1]; ok {continue}offset := 0for {offset++_, ok := m[num + offset]if !ok {break}}ans = max(ans, offset)}return ans
}
题解链接
https://leetcode.cn/problems/longest-consecutive-sequence/