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
}
相关推荐
鹏北海-RemHusband7 小时前
Go 语言进阶笔记 — 面向 JS/TS 前端开发者
笔记·golang
罗超驿12 小时前
9.LeetCode 209. 长度最小的子数组 | 滑动窗口专题详解
java·算法·leetcode·面试
水蓝烟雨12 小时前
0135. 分发糖果
算法·leetcode
如竟没有火炬13 小时前
乘法表中第K小的数——二分
开发语言·数据结构·python·算法·leetcode·职场和发展·动态规划
诚威_lol_中大努力中15 小时前
Hot-146 LRU(最近最少使用Least Recent Use)缓存
leetcode
x_xbx16 小时前
LeetCode:739. 每日温度
算法·leetcode·职场和发展
Starry-sky(jing)16 小时前
Hermes Agent 接入 Qwen3.7-Max 报 401?OpenCode Go 模型路由源码级排查与修复
开发语言·人工智能·chrome·golang
鹏北海-RemHusband16 小时前
Go 语言基础笔记 — 面向 JS/TS 前端开发者
笔记·golang
圣保罗的大教堂17 小时前
leetcode 3121. 统计特殊字母的数量 II 中等
leetcode
圣保罗的大教堂17 小时前
leetcode 3120. 统计特殊字母的数量 I 简单
leetcode