func longestConsecutive(nums []int) int {
type Set map[int]struct{}
// numsSet := map[int]struct{}
numsSet := make(Set)
for _, num := range nums {
numsSet[num] = struct{}{}
}
res := 0
for num := range numsSet {
if _, ok := numsSet[num-1]; ok {
curNum := num
curRes := 1
for _, ok := numsSet[curNum+1]; ok {
curNum++
curRes++
}
if curRes > res {
res = curRes
}
}
}
return res
}
两点疑问:
numsSet := map[int]struct{}
为什么无法编译,必须以下写法才能运行type Set map[int]struct{}
numsSet := make(Set)
for _, ok := numsSet[curNum+1]; ok { curNum++ curRes++ }
这里for循环遍历无法编译,正确写法是什么?改成下面写法可以运行,能不能合成一句?
for { if _, ok := numsSet[curNum+1]; ok{ curNum++ curRes++ } else if !ok { break } }
numsSet := map[int]struct{}
不能编译,因为map[int]struct{}
是类型而不是字面量。其中int
是键类型,struct{}
是值类型。可以改为numsSet := map[int]struct{}{}
。go 的 for 语法形式中没有类似 if 的特殊写法。
for {}
for i := 0 ; i < 10; i++ {}
for i := range make(chan int, 1) {}
for k,v := range map[int]int{} {}
for idx, v := range []int{1,2,3} {}