dougou8458 2018-02-02 14:42
浏览 72
已采纳

hackerrank圆形数组旋转执行时错误

I did solved a hackerrank problem which is "Circular Array Rotation" using Go when i run the code it gives me a correct response and when i try to submit the code all the test passes except one and it says Runtime Error

I tried the failing test localy and it passes my code is

    package main
    import "fmt"

    func CircularArrayRotation() {
        var n, k, q int

        fmt.Scanf("%d%d%d", &n, &k, &q)
        a := make([]int, n)
        for i := range a {
            fmt.Scanf("%d", &a[i])
        }

        var i int
        for t:=0; t<q; t++  {

            fmt.Scanf("%d", &i)
            j := (i - k)
            if j<0 {
                j+=n
            }

            fmt.Println(a[j])
        }

    }

func main() {
 //Enter your code here. Read input from STDIN. Print output to STDOUT
    CircularArrayRotation()
}
  • 写回答

2条回答 默认 最新

  • dswg47377 2018-02-02 14:51
    关注

    For those that want more information you can look here: https://www.hackerrank.com/challenges/circular-array-rotation/problem

    The Input for his failing case is this and the Expected Output is this

    Your run time error is this:

    panic: runtime error: index out of range

    goroutine 1 [running]: main.CircularArrayRotation() solution.go:22
    +0x349 main.main() solution.go:29 +0x20

    So your issue is on line 22, where your index is out of range: fmt.Println(a[j])

    This happens because your code currently cannot handle multiple rotations, so in your code you end up executing the following:

    fmt.Println(a[-99477])
    

    This happens when i is 8 and k is 100000

    Imagine you had this input:

    n = 3
    k = 10
    q = 1
    i = 2

    When you perform i - k we get -8, we then try to add n which gives us -5 (-8 + 3), then we try to access an index that does not exist. a[-5]

    If you wish to fix this issue you can do the below (inside spoiler in case you want to work this out yourself):

    put this above your i - k
    k = k % n

    The reason this fixes your code is:

    It works out how many rotations are left after we've fully looped x times. That way we don't have to worry about multiple rotations.

    --
    As a side note for this challenge there's some interesting stuff you can do with slices for rotating an array using some of the stuff covered here: https://tour.golang.org/moretypes/10

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?