猿问

如何为数组的最后一个元素添加特殊条件

根据任务描述,输出应该是一个新数组,其中数组 days 的所有元素都大于其上一个和下一个元素(以 1 为增量)。例如,我们有作为输入


[ ]int{3, 2, 4, 3, 7, 9}

输出应该是:


[ ]int{3, 4, 9}

起初我试着写下一个条件:


if days[i] > days[i-1] && days[i] > days[i+1] {

            arr = append(arr, days[i])

        }

但发生错误:index out of range [-1]


然后我改变了条件并为最后一个元素添加了一个特殊条件:


package main


import (

    "fmt"

)


func chaos(days []int) []int {

    var arr []int

    for i := 0; i < len(days)-1; i++ {

        if days[i] > days[i+1] {

            arr = append(arr, days[i])

        }

        if days[len(days)-1] > days[len(days)-2] {

            arr = append(arr, days[len(days)-1])

        }

    }

    return arr

}


func main() {

    fmt.Println(chaos([]int{3, 2, 4, 3, 7, 9}))

}

但输出是[3 9 9 4 9 9 9]


如何正确指定最后一个元素的条件以及为什么我的结果不正确?


莫回无
浏览 79回答 2
2回答

宝慕林4294392

9多次填充的原因是因为您在循环if内使用以下条件for。将其放在循环if之外for,然后您将获得所需的输出:if days[len(days)-1] > days[len(days)-2] {&nbsp; &nbsp; &nbsp; &nbsp; arr = append(arr, days[len(days)-1])&nbsp; &nbsp; }但是,除此之外,您还只是将i'th元素与下一个元素进行比较。根据问题,您还应该将它与之前的元素进行比较。以下是可以在您的代码中进行的可能更改以正常工作:package mainimport (&nbsp; &nbsp; "fmt")func chaos(days []int) []int {&nbsp; &nbsp; var arr []int&nbsp; &nbsp; fmt.Println(len(days))&nbsp; &nbsp; if days[0] > days[1] {&nbsp; &nbsp; &nbsp; &nbsp; arr = append(arr, days[0])&nbsp; &nbsp; }&nbsp; &nbsp; for i := 1; i < len(days)-1; i++ {&nbsp; &nbsp; &nbsp; &nbsp; if (days[i] > days[i+1]) && (days[i] > days[i-1]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr = append(arr, days[i])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if days[len(days)-1] > days[len(days)-2] {&nbsp; &nbsp; &nbsp; &nbsp; arr = append(arr, days[len(days)-1])&nbsp; &nbsp; }&nbsp; &nbsp; return arr}func main() {&nbsp; &nbsp; fmt.Println(chaos([]int{3, 2, 4, 3, 7, 9}))}https://go.dev/play/p/ndJVc35TM1O

智慧大石

您可以将math.MinInt64(可以视为负无穷大)添加到切片的开始和结束,以轻松处理两种边缘情况。然后从一个索引开始迭代1到另一个索引n-2(通过排除0和n-1我们添加的条目)。我会像下面那样尝试。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math")func chaos(days []int) []int {&nbsp; &nbsp; var arr []int&nbsp; &nbsp; // Add negative infinity to the start&nbsp; &nbsp; days = append([]int{math.MinInt64}, days...)&nbsp; &nbsp; // Add negative infinity to the end&nbsp; &nbsp; days = append(days, math.MinInt64)&nbsp; &nbsp; for i := 1; i <= len(days)-2; i++ {&nbsp; &nbsp; &nbsp; &nbsp; if (days[i] > days[i+1]) && (days[i] > days[i-1]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr = append(arr, days[i])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return arr}func main() {&nbsp; &nbsp; fmt.Println(chaos([]int{3, 2, 4, 3, 7, 9}))}
随时随地看视频慕课网APP

相关分类

Go
我要回答