diff --git "a/problems/kamacoder/0058.\345\214\272\351\227\264\345\222\214.md" "b/problems/kamacoder/0058.\345\214\272\351\227\264\345\222\214.md" index 23e7189a15..7e89373e10 100644 --- "a/problems/kamacoder/0058.\345\214\272\351\227\264\345\222\214.md" +++ "b/problems/kamacoder/0058.\345\214\272\351\227\264\345\222\214.md" @@ -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]) + } +} +```