dragon8997474 2019-09-23 20:30
浏览 289

如何在golang中转换或移位slice中的值?

I have a slice in golang, say [1 2 3 4 5 6 7 8 9 10], and I would like to efficiently shift the values to different indexes such as a shift of 5 would yield [6 7 8 9 10 1 2 3 4 5].

I have come up with a solution below, but wondering if there is a built-in or better way to accomplish this?

https://play.golang.org/p/tkYPkGmffQ1

  • 写回答

2条回答 默认 最新

  • doubu0897 2019-09-23 20:46
    关注
    func translation(nums []int, n int) []int {
        n = n % len(nums)
        return append(nums[n:len(nums):len(nums)], nums[:n]...)
    }
    

    is sufficient.

    nums[n:len(nums):len(nums)] is a "full slice expression" which ensures that the resulting slice has no excess capacity (even if nums does). Since it has 0 extra capacity, append will have to allocate a new array to place the extra items, and the returned slice won't be an alias of the original slice — unless n is 0. If you need to handle the case of 0, then you can do it with a copy.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器