我正在研究算法,它只在 1 种情况下给出错误(运行时错误)

I'm working on the algorithm and it only gives an error in 1 case (Runtime Error)

只有情况 4 给出了运行时错误。我查看了其他答案,但找不到解决方案

Question

我不return数组。我只是添加元素

func circularArrayRotation(a: [Int], k: Int, queries: [Int]) -> [Int] {
    var result = [Int]()
    
    for i in queries {
        if i < k {
            result.append(a[a.count-k+i])
        }
        else {
            result.append(a[i-k])
        }
    }
    return result
}

这个算法的时间复杂度不就是O(n)吗。我算错了吗?

k 可以比数组的长度大得多,所以你的方法失败了,因为索引比数组长度大得多。

要正确处理此问题,请使 k 等于 k modulus array_length,因为将数组旋转 array_length 次实际上不会改变当前顺序。