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
}
相关推荐
OYangxf13 分钟前
力扣hot100【子串专题】
算法·leetcode·职场和发展
玛卡巴卡ldf2 小时前
【LeetCode 手撕算法】(二分查找)搜索插入位置、搜索二维矩阵、查找数组相同的所有位置、搜索旋转排序数组、旋转升序数组的最小值
数据结构·算法·leetcode
jieyucx9 小时前
Go语言深度解剖:Map扩容机制全解析(增量扩容+等量扩容+渐进式迁移)
开发语言·后端·golang·map·扩容策略
刃神太酷啦9 小时前
扒透 STL 底层!map/set 如何封装红黑树?迭代器逻辑 + 键值限制全手撕----《Hello C++ Wrold!》(23)--(C/C++)
java·c语言·javascript·数据结构·c++·算法·leetcode
王码码203510 小时前
Go语言的内存管理:原理与实战
后端·golang·go·接口
_深海凉_11 小时前
LeetCode热题100-分割回文串
算法·leetcode·职场和发展
~|Bernard|13 小时前
一.go语言中slice底层原理(2026-5-7)
golang·go
流年如夢14 小时前
单链表Ⅲ(LeetCode)
数据结构·算法·leetcode·职场和发展
~|Bernard|16 小时前
二.go语言中map的底层原理(2026-5-8)
算法·golang·哈希算法
mask哥16 小时前
力扣算法java实现汇总整理(下)
java·算法·leetcode