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
}
相关推荐
wabs6662 小时前
关于动态规划【力扣1143.最长公共子序列的思考】
算法·leetcode·动态规划
剑挑星河月2 小时前
54.螺旋矩阵
java·算法·leetcode·矩阵
笨笨没好名字4 小时前
Leetcode刷题python3版第一周(下)
linux·算法·leetcode
想你依然心痛4 小时前
AtomCode在后端开发中的实战体验:Go微服务从零搭建
开发语言·微服务·golang
王老师青少年编程5 小时前
2026年6月GESP真题及题解(C++五级):排排坐
c++·题解·真题·gesp·五级·2026年6月·排排坐
开发小程序的之朴5 小时前
认识安企CMS - 系统概述
nginx·golang·系统架构
雨师@5 小时前
go语言项目--实例化(图书管理)--005
开发语言·后端·golang
Vect__5 小时前
Go 数据结构 slice 深度剖析
开发语言·数据结构·golang
geovindu5 小时前
go: Functional Options Pattern
开发语言·后端·设计模式·golang·函数式选项模式’·惯用法模式
青山木6 小时前
Hot 100 --- LRU 缓存
java·数据结构·算法·leetcode·链表·缓存·哈希