Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fcbc233

Browse files
author
haoc
committed
add: 128
1 parent db4185c commit fcbc233

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
2+
# 0128.longest-consecutive-sequence
3+
4+
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
5+
6+
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
7+
8+
9+
10+
示例 1:
11+
12+
输入:nums = [100,4,200,1,3,2]
13+
输出:4
14+
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
15+
示例 2:
16+
17+
输入:nums = [0,3,7,2,5,8,4,6,0,1]
18+
输出:9
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package sequence
2+
3+
import "fmt"
4+
5+
func Run() {
6+
//nums := []int{100, 1, 200, 2, 3}
7+
nums := []int{0, 3, 7, 2, 5, 8, 4, 6, 0, 1}
8+
l := longestConsecutive(nums)
9+
fmt.Println(l)
10+
}
11+
12+
func longestConsecutive(nums []int) int {
13+
length := 0
14+
if len(nums) == 0 {
15+
return length
16+
}
17+
numsMap := make(map[int]bool, len(nums))
18+
for _, num := range nums {
19+
numsMap[num] = true
20+
}
21+
for num := range numsMap {
22+
if numsMap[num-1] {
23+
continue
24+
}
25+
curLength := 1
26+
curNum := num
27+
for numsMap[curNum+1] {
28+
curLength++
29+
curNum++
30+
}
31+
if length < curLength {
32+
length = curLength
33+
}
34+
}
35+
return length
36+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
package sequence
3+
4+
import "testing"
5+
6+
func TestRun(t *testing.T) {
7+
Run()
8+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /