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
}
相关推荐
mmmmath_34 小时前
LeetCode.199.二叉树的右视图
数据结构·leetcode
microrain9 小时前
读数是 1008,用电量是 8:SagooIoT 计算服务的增量口径与七种计算策略
物联网·golang·计算服务·sagooiot
Nil2089 小时前
leetcode 198打家劫舍
算法·leetcode·职场和发展
mmmmath_39 小时前
LeetCode.429.N叉树的层序遍历
数据结构·leetcode
看浪的路人11 小时前
第7讲:大模型后端服务化——Go 实现高并发 LLM Proxy / Router / Fallback
开发语言·后端·golang
灯澜忆梦14 小时前
【Go Zap 日志库】#1 |快速上手 + 配置详解
开发语言·后端·golang
INGNIGHT15 小时前
593 · 石头游戏 II (区间dp石子合并 翻倍循环问题)
leetcode
aqiu11111115 小时前
【C++算法打怪专栏】LeetCode 402. 移掉 K 位数字(单调栈 + 贪心)
c++·算法·leetcode
第六种自由16 小时前
[路飞]_Leetcode 22. 括号生成
javascript·算法·leetcode
不是万能的豆学长16 小时前
排查Go服务40天后的内存泄漏问题
开发语言·后端·golang·go