Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f8faa26

Browse files
author
侯利朋
committed
.\128.最长连续序列 ok map
1 parent e2102ac commit f8faa26

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

128.最长连续序列-sort-nlogn.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import "sort"
2+
3+
/*
4+
* @lc app=leetcode.cn id=128 lang=golang
5+
*
6+
* [128] 最长连续序列
7+
*/
8+
// 8 ms, faster than 46.27%
9+
// 法1:排序后查找,O(nlogn),不满足题目要求
10+
func longestConsecutive(nums []int) int {
11+
if len(nums) == 0 {
12+
return 0
13+
}
14+
sort.Ints(nums)
15+
16+
curLen := 1
17+
maxLen := 1
18+
for i := 1; i < len(nums); i++ { // 从1开始计算
19+
if nums[i] == nums[i-1] {
20+
// 重复元素,计数不更新
21+
} else if nums[i] == nums[i-1]+1 {
22+
curLen++
23+
} else {
24+
if curLen > maxLen {
25+
maxLen = curLen
26+
}
27+
curLen = 1
28+
}
29+
}
30+
if curLen > maxLen { // 统计最后一段的长度
31+
maxLen = curLen
32+
}
33+
return maxLen
34+
}

128.最长连续序列.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* @lc app=leetcode.cn id=128 lang=golang
3+
*
4+
* [128] 最长连续序列
5+
*/
6+
// 4 ms, faster than 96.52%
7+
// 法1:排序后查找,O(nlogn),不满足题目要求
8+
// 法2: map缓存。下面是实现方式
9+
func longestConsecutive(nums []int) int {
10+
if len(nums) == 0 || len(nums) == 1 {
11+
return len(nums)
12+
}
13+
14+
buf := make(map[int]bool, len(nums))
15+
for i := 0; i < len(nums); i++ {
16+
buf[nums[i]] = true
17+
}
18+
19+
curLen := 0
20+
maxLen := 1
21+
for _, v := range nums {
22+
if buf[v-1] { // 一定注意,此处是对v-1进行判断,如果不存在,表示v是一个序列的开始
23+
continue
24+
}
25+
curLen = 0
26+
for buf[v] {
27+
v++
28+
curLen++
29+
}
30+
if curLen > maxLen {
31+
maxLen = curLen
32+
}
33+
}
34+
if curLen > maxLen {
35+
maxLen = curLen
36+
}
37+
return maxLen
38+
}

0 commit comments

Comments
 (0)