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
}
相关推荐
利威尔xu5 小时前
Go context取消传播3层:信号传不到第3层goroutine,泄漏拖垮
后端·golang
Sakura_j_h_8 小时前
TypeScript 7.0 换 Go 编译器后,我先在 6.0 清完默认值
javascript·golang·typescript·vite·前端工程化·tsc
旖旎夜光1 天前
LeetCode 493: 翻转对 (归并排序) —— 题解
c++·笔记·学习·算法·leetcode·排序算法
木井巳1 天前
【动态规划: 子序列问题】最长递增子序列的个数
java·算法·leetcode·动态规划·推荐算法
码途行者1 天前
每天10分钟学Go:第23课 协程(goroutine)
开发语言·后端·golang
利威尔xu1 天前
2026-11-25-Go-panic-recover面试
面试·golang
码途行者1 天前
每天10分钟学Go:第24课 通道-协程之间的传送带
开发语言·后端·golang
Navigator_Z1 天前
LeetCode //C - 1326. Minimum Number of Taps to Open to Water a Garden
c语言·算法·leetcode
Rain的Java大神之路2 天前
LeetCode 45 跳跃游戏 II:大厂面试官最爱追问的贪心题,我把骨头给你拆干净了
java·后端·leetcode
让我们一起加油好吗3 天前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试