登录
首页 >  Golang >  Go问答

运行时错误:数组越界

来源:stackoverflow

时间:2024-02-09 13:36:23 307浏览 收藏

哈喽!今天心血来潮给大家带来了《运行时错误:数组越界》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

当我尝试解决118的leetcode问题时。帕斯卡三角形 https://leetcode.com/problems/pascals-triangle/

发生了奇怪的错误。下面的代码可以通过oj。

func generate(numrows int) [][]int {
    res := [][]int{}
    for i := 0; i < numrows; i++ {
        row := []int{}
        for j := 0; j < i+1; j++ {
            if j == 0 || j == i {
                row = append(row, 1)
            } else if i > 1 {
                row = append(row, res[i-1][j-1] + res[i-1][j])
            }
        }
        res = append(res, row)
    }
    return res
}

但是我这样写的代码会出现panic,但是基本逻辑是一样的。

func generate(numRows int) [][]int {
    res := [][]int{}
    for i := 0; i < numRows; i++ {
        row := []int{}
        for j := 0; j < i+1; j++ {
            if j == 0 || j == i {
                row = append(row, 1)
            }
            if i > 1 {
                row = append(row, res[i-1][j-1] + res[i-1][j])
            }
        }
        res = append(res, row)
    }
    return res
}

我用了if else if结构,效果很好,但是我用了2个if条件判断错误。

其实他们的逻辑是一样的,但是为什么会出错呢?如果您能解决这个问题,我将不胜感激。祝你好运!


正确答案


问题是您在第二个版本中使用了 2 个 if 条件,而在第一个版本中您有一个 if else

不,逻辑不一样。结果是当 j 为 0 时,您尝试执行 j-1

如果有 2 个这样的 if 条件,如果满足各自的条件,程序将分别输入这两个块。

if j == 0 || j == i {
    row = append(row, 1)
}
// if j is 0 you still enter this block as long as i > 1
if i > 1 {
    row = append(row, res[i-1][j-1] + res[i-1][j])
}

如果满足第一个 if,您可以使用 continue 跳过此部分。

if j == 0 || j == i {
    row = append(row, 1)
    // continue with the next iteration
    continue
}
if i > 1 {
    row = append(row, res[i-1][j-1] + res[i-1][j])
}

也就是说,在代码的第一个版本中使用 if else 似乎是合理的。我不确定您为什么要更改它。

终于介绍完啦!小伙伴们,这篇关于《运行时错误:数组越界》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>