最长连续序列
題目:
? ? 給定一個未排序的整數數組,找出最長連續序列的長度。
? ? 要求算法的時間復雜度為?O(n)。
示例:
輸入:?[100, 4, 200, 1, 3, 2]輸出: 4解釋: 最長連續序列是 [1, 2, 3, 4]。它的長度為 4。 func longestConsecutive(nums []int) int {//哈希表numSet := map[int]bool{}for _, num := range nums {numSet[num] = true}longestStreak := 0for num := range numSet {if !numSet[num-1] {currentNum := numcurrentStreak := 1for numSet[currentNum+1] {currentNum++currentStreak++}if longestStreak < currentStreak {longestStreak = currentStreak}}}return longestStreak }只有當一個數是連續序列的第一個數的情況下才會進入內層循環,然后在內層循環中匹配連續序列中的數。?if !numSet[num-1] 是思維的重點,同時也要注意哈希表的用法,哈希表可以用來排序。
?
代碼地址:https://leetcode-cn.com/problems/longest-consecutive-sequence/solution/zui-chang-lian-xu-xu-lie-by-leetcode-solution/
?
總結
- 上一篇: 二叉树中最大路径和
- 下一篇: 二叉树的序列化与反序列化