Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

更新:添加kamacoder/0058区间和的Go版本 #2896

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions problems/kamacoder/0058.区间和.md
Original file line number Diff line number Diff line change
Expand Up @@ -357,3 +357,54 @@ int main(int argc, char *argv[])

```

### Go

```go
package main

import (
"fmt"
"bufio"
"strconv"
"os"
)

func main() {
// bufio中读取数据的接口,因为数据卡的比较严,导致使用fmt.Scan会超时
scanner := bufio.NewScanner(os.Stdin)

// 获取数组大小
scanner.Scan()
n, _ := strconv.Atoi(scanner.Text())

// 获取数组元素的同时计算前缀和,一般建议切片开大一点防止各种越界问题
arr := make([]int, n + 1)
for i := 0; i < n; i++ {
scanner.Scan()
arr[i], _ = strconv.Atoi(scanner.Text())
if i != 0 {
arr[i] += arr[i - 1]
}
}

/*
区间[l, r]的和可以使用区间[0, r]和[0, l - 1]相减得到,
在代码中即为arr[r]-arr[l-1]。这里需要注意l-1是否越界
*/
for {
var l, r int
scanner.Scan()
_, err := fmt.Sscanf(scanner.Text(), "%d %d", &l, &r)
if err != nil {
return
}

if l > 0 {
fmt.Println(arr[r] - arr[l - 1])
} else {
fmt.Println(arr[r])
}
}
}
```