arrays - 我不断收到索引超出范围错误,我的代码有什么问题?

标签 arrays go slice

我的代码无法正常运行 我试图让它找到包括数组结尾和开头的峰值,然后将所有不是开头或结尾的索引与它们之前和之后的索引进行比较知道为什么我会收到超出索引范围的错误吗?

package main

import "fmt"

func linearFindPeaks(arg []int) []int {
    peaks := []int{}
    lenArg := len(arg)
    for i := 0; i < lenArg; i++ {
        //if its the first element run this
        //second if statement for the end of array
        // for default statements
        if arg[0] > arg[1] {
            peaks = append(peaks, arg[0])
        } else if arg[lenArg-1] > arg[lenArg-2] {
            peaks = append(peaks, arg[lenArg-1])
        } else if arg[i] > arg[i+1] && arg[i] > arg[i-1] && arg[i] != arg[0] && arg[i] != arg[lenArg-1] {
            peaks = append(peaks, arg[i])
        }
    }
    fmt.Println(peaks)
    return peaks
}

func main() {}

Playground :https://play.golang.org/p/2JRgEyRA50

最佳答案

我可以看到两种可能性。首先,在第一个 else if 中:

}else if arg[lenArg - 1] > arg[lenArg -2] {

如果 lenArg1,则 lenArg-2 将为 -1。这意味着 arg[lenArg-2]arg[-1],它会让你越界。

其次,在第二个else if中:

} else if arg[i] > arg[i+1] ... {

在循环的最后一次迭代中,i 将为 lenArg-1,如果您将 1 添加到此,您将得到 arg[lenArg-1+1]arg[lenArg] 将越界。 (最后一个可用索引位于 lenArg-1)

关于arrays - 我不断收到索引超出范围错误,我的代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47404608/

相关文章:

java - 如何在java中的任何二维数组中存储不同数据类型的多个字段?

google-app-engine - 在 App Engine 上的 Go 中建模 N 到 N 关联

node.js - 使用socket.io连接node js服务器和golang服务器有什么缺点?

Python:选择具有更改值的行

javascript - 如何将 JavaScript (Node.js) 数组转换为 C# 字符串数组?

ios - Swift 3 For 循环比较和更改

ruby - 带小数位的范围

go - 如何使用 uint32s 提供随机源

Python:带有间隙的切片的语法更短?

arrays - 在 Go 中,为什么 a[1 :] not give an index out of bounds error for a capacity = 1 slice?