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
}
相关推荐
203号居民10 小时前
LeetCode hot 100 — 141. 环形链表2
算法·leetcode·链表
xcLeigh10 小时前
Go入门:整数类型的溢出与安全边界
java·安全·golang
玖玥拾11 小时前
LeetCode 202 快乐数
算法·leetcode
Tim_1012 小时前
【LeetCode】29、两数相除
算法·leetcode·职场和发展
lvwangshu15 小时前
P6534 [COCI 2015/2016 #1] UZASTOPNI 等差树列 题解
动态规划·图论·题解·性质题
ttwuai17 小时前
Go 后台附件迁到对象存储后,path、cdnUrl 和 tenant_id 怎么一起验?
开发语言·后端·golang
ttwuai18 小时前
Go 后台清空操作日志失败,权限和无 WHERE 删除怎么排查?
开发语言·后端·golang
gsls20080819 小时前
OpsKat封装MCP:用 Go 标准库把运维 CLI 变成 AI 的“手“
运维·人工智能·golang·mcp
土司大王19 小时前
LeetCode hot100——缺失的第一个正数
数据结构·算法·leetcode
Cccp.12319 小时前
【leetcode】(二)认识O(NlogN)的排序
算法·leetcode