Skip to content

Commit b489cb6

Browse files
Merge pull request #2896 from HuangLM03/update-kamacoder/0058区间和
更新:添加kamacoder/0058区间和的Go版本
2 parents 86a0208 + da82173 commit b489cb6

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

problems/kamacoder/0058.区间和.md

+51
Original file line numberDiff line numberDiff line change
@@ -357,3 +357,54 @@ int main(int argc, char *argv[])
357357

358358
```
359359
360+
### Go
361+
362+
```go
363+
package main
364+
365+
import (
366+
"fmt"
367+
"bufio"
368+
"strconv"
369+
"os"
370+
)
371+
372+
func main() {
373+
// bufio中读取数据的接口,因为数据卡的比较严,导致使用fmt.Scan会超时
374+
scanner := bufio.NewScanner(os.Stdin)
375+
376+
// 获取数组大小
377+
scanner.Scan()
378+
n, _ := strconv.Atoi(scanner.Text())
379+
380+
// 获取数组元素的同时计算前缀和,一般建议切片开大一点防止各种越界问题
381+
arr := make([]int, n + 1)
382+
for i := 0; i < n; i++ {
383+
scanner.Scan()
384+
arr[i], _ = strconv.Atoi(scanner.Text())
385+
if i != 0 {
386+
arr[i] += arr[i - 1]
387+
}
388+
}
389+
390+
/*
391+
区间[l, r]的和可以使用区间[0, r]和[0, l - 1]相减得到,
392+
在代码中即为arr[r]-arr[l-1]。这里需要注意l-1是否越界
393+
*/
394+
for {
395+
var l, r int
396+
scanner.Scan()
397+
_, err := fmt.Sscanf(scanner.Text(), "%d %d", &l, &r)
398+
if err != nil {
399+
return
400+
}
401+
402+
if l > 0 {
403+
fmt.Println(arr[r] - arr[l - 1])
404+
} else {
405+
fmt.Println(arr[r])
406+
}
407+
}
408+
}
409+
```
410+

0 commit comments

Comments
 (0)