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
}
相关推荐
名字还没想好☜1 小时前
Go 的 time.Ticker 陷阱:定时任务里被忽略的内存泄漏与正确关闭
java·数据库·golang·go·定时器
Navigator_Z5 小时前
LeetCode //C - 1156. Swap For Longest Repeated Character Substring
c语言·算法·leetcode
灯澜忆梦7 小时前
Go 语言 _JSON---序列化与反序列化
开发语言·golang·json
布朗克1688 小时前
Go入门到精通-22-同步原语
开发语言·后端·golang·同步原语
兰令水8 小时前
hot100【acm版】【2026.7.19打卡-java版本】
java·数据结构·算法·leetcode·面试
怒放de生命20109 小时前
【web3基础】go-zero使用etcd实现服务注册与发现(四)
golang·web3·etcd·go-zero
tkevinjd10 小时前
力扣72-编辑距离
算法·leetcode·职场和发展
qz5zwangzihan111 小时前
题解:Atcoder Beginner Contest abc467 A~D
c++·题解·atcoder·abc467
Wang's Blog19 小时前
Go-Zero项目开发4: 用户服务搜索、详情与统一错误处理
开发语言·golang
什巳1 天前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode