8000 summary_ranges · hitzzc/go-leetcode@103e107 · GitHub
[go: up one dir, main page]

Skip to content

Commit 103e107

Browse files
committed
summary_ranges
1 parent bde3c2b commit 103e107

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
184184
#### [225. Implement Stack using Queues](https://github.com/hitzzc/go-leetcode/tree/master/implement_stack_using_queues)
185185
#### [226. Invert Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/invert_binary_tree)
186186
#### [227. Basic Calculator II](https://github.com/hitzzc/go-leetcode/tree/master/basic_calculator_II)
187+
#### [228. Summary Ranges](https://github.com/hitzzc/go-leetcode/tree/master/summary_ranges)
187188

188189

189190

summary_ranges/summary_ranges.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package summary_ranges
2+
3+
import (
4+
"strconv"
5+
)
6+
7+
func summaryRanges(nums []int) []string {
8+
var ret []string
9+
if len(nums) == 0 {
10+
return ret
11+
}
12+
if len(nums) == 1 {
13+
return []string{strconv.Itoa(nums[0])}
14+
}
15+
var i int
16+
var j int = 1
17+
for ; j < len(nums); j++ {
18+
if nums[j] == nums[j-1]+1 {
19+
continue
20+
}
21+
if nums[j] != nums[j-1]+1 {
22+
if j-1 == i {
23+
ret = append(ret, strconv.Itoa(nums[i]))
24+
} else {
25+
ret = append(ret, strconv.Itoa(nums[i])+"->"+strconv.Itoa(nums[j-1]))
26+
}
27+
i = j
28+
}
29+
}
30+
if j-1 == i {
31+
ret = append(ret, strconv.Itoa(nums[i]))
32+
} else {
33+
ret = append(ret, strconv.Itoa(nums[i])+"->"+strconv.Itoa(nums[j-1]))
34+
}
35+
return ret
36+
}

0 commit comments

Comments
 (0)
0