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

添加 0058.区间和.md Go版本 #2881

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
42 changes: 42 additions & 0 deletions problems/kamacoder/0058.区间和.md
Original file line number Diff line number Diff line change
Expand Up @@ -357,3 +357,45 @@ int main(int argc, char *argv[])

```

### Go

```go
package main

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

func main() {
// fmt效率慢导致超时,使用bufio替代fmt读取输入提高效率
scanner := bufio.NewScanner(os.Stdin)

// 读取前缀和数组长度
scanner.Scan()
n, _ := strconv.Atoi(scanner.Text())

// 读取数组元素并计算前缀和
prefixSum := make([]int, n+1)
for i := 1; i <= n; i++ {
scanner.Scan()
num, _ := strconv.Atoi(scanner.Text())
prefixSum[i] = prefixSum[i-1] + num
}

// 读取查询并计算区间和
for scanner.Scan() {
line := scanner.Text()
indices := strings.Split(line, " ")
if len(indices) < 2 {
continue
}
a, _ := strconv.Atoi(indices[0])
b, _ := strconv.Atoi(indices[1])
fmt.Println(prefixSum[b+1] - prefixSum[a])
}
}
```