我不断使索引超出范围错误我的代码有什么问题?

My code won't run properly I am trying to get it to find peaks including the end and beginning of the array and then compare all the indexes that aren't the beginning or end to the index before and after them does anyone know why I am getting the out of index range error?

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

Two possibilities i can see. Firstly, in the first else if:

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

If lenArg is 1 then lenArg-2will be -1. This means arg[lenArg-2] is arg[-1] which will give you out of bounds.

Secondly, in the second else if:

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

On the last iteration over the loop, i will be lenArg-1, if you add 1 to this you'll get arg[lenArg-1+1] or arg[lenArg] which will out of bounds. (The last available index is at lenArg-1)

The Go Programming Language Specification

Index expressions

A primary expression of the form

a[x]

denotes the element of the slice a indexed by x.

The index x must be of integer type or untyped; it is in range if

0 <= x < len(a)

Otherwise it is out of range.


You need to pay attention to corner cases like lengths 0, 1, and 2 for indices i - 1, i, i + 1 out of range. For example,

package main

// For array a, a[i] is a peak if it is not smaller than its neighbor(s),
// where a[-1] = a[n] = -∞.
func findPeaks(a []int) []int {
    var p []int
    // special cases
    if len(a) == 0 {
        return p
    }
    if len(a) == 1 {
        return append(p, a[0])
    }
    // first
    i := 0
    if a[i] >= a[i+1] {
        p = append(p, a[i])
    }
    // first < i < last
    for i = 1; i < len(a)-1; i++ {
        if a[i-1] <= a[i] && a[i] >= a[i+1] {
            p = append(p, a[i])
        }
    }
    // last
    i = len(a) - 1
    if a[i-1] <= a[i] {
        p = append(p, a[i])
    }
    return p
}

func main() {}

Playground: https://play.golang.org/p/9klj1wYnXZ