Golang | Leetcode Golang题解之第457题环形数组是否存在循环

题目:

题解:

Go 复制代码
func circularArrayLoop(nums []int) bool {
    n := len(nums)
    next := func(cur int) int {
        return ((cur+nums[cur])%n + n) % n // 保证返回值在 [0,n) 中
    }

    for i, num := range nums {
        if num == 0 {
            continue
        }
        slow, fast := i, next(i)
        // 判断非零且方向相同
        for nums[slow]*nums[fast] > 0 && nums[slow]*nums[next(fast)] > 0 {
            if slow == fast {
                if slow == next(slow) {
                    break
                }
                return true
            }
            slow = next(slow)
            fast = next(next(fast))
        }
        add := i
        for nums[add]*nums[next(add)] > 0 {
            tmp := add
            add = next(add)
            nums[tmp] = 0
        }
    }
    return false
}
相关推荐
枫景Maple9 小时前
LeetCode 2297. 跳跃游戏 VIII(中等)
算法·leetcode
roman_日积跬步-终至千里12 小时前
【Go语言基础【9】】字符串格式化与输入处理
golang
緈福的街口13 小时前
【leetcode】3. 无重复字符的最长子串
算法·leetcode·职场和发展
小刘不想改BUG16 小时前
LeetCode 70 爬楼梯(Java)
java·算法·leetcode
比特森林探险记17 小时前
Go 中的 Map 与字符处理指南
c++·算法·golang
比特森林探险记17 小时前
Go 中 map 的双值检测写法详解
java·前端·golang
哆啦A梦158817 小时前
在golang中如何将已安装的依赖降级处理,比如:将 go-ansible/[email protected] 更换为 go-ansible/@v1.1.7
开发语言·golang·ansible
LanLance18 小时前
ES101系列09 | 运维、监控与性能优化
java·运维·后端·elasticsearch·云原生·性能优化·golang
sz66cm18 小时前
LeetCode刷题 -- 542. 01矩阵 基于 DFS 更新优化的多源最短路径实现
leetcode·矩阵·深度优先