Leetcode Note: Go - Summary Ranges
Summary Ranges - LeetCode
https://leetcode.com/problems/summary-ranges/
- Go 言語で取り組んだメモ
所感
- 問題文の解釈が難しい
回答
Golang : faster than 100.00% of Go online submissions - LeetCode Discuss
https://leetcode.com/problems/summary-ranges/discuss/402364/Golang-%3A-faster-than-100.00-of-Go-online-submissions
func summaryRanges(nums []int) []string {
if len(nums) == 0 {
return nil
}
var summaryRanges []string
var head int = 0
for i := range nums {
if (i < len(nums)-1 && nums[i]+1 == nums[i+1]) {
continue
}
if head == i {
summaryRanges = append(summaryRanges, strconv.Itoa(nums[i]))
} else {
tmp := strconv.Itoa(nums[head]) + "->" + strconv.Itoa(nums[i])
summaryRanges = append(summaryRanges, tmp)
}
head = i + 1
}
return summaryRanges
}
- 色々問題文に対する解釈違いがあったが range でループ回しつつ、次の要素との比較を行うために自前の index を用意するという実装で突破