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
}
相关推荐
脚踏实地的大梦想家2 小时前
【Go】P2 Golang 常量与变量
开发语言·后端·golang
张璐月2 小时前
go docker-compose启动前后端分离项目 踩坑之旅
开发语言·docker·golang
Swift社区2 小时前
Swift 解法详解:LeetCode 371《两整数之和》
开发语言·leetcode·swift
Swift社区2 小时前
Swift 解法详解 LeetCode 362:敲击计数器,让数据统计更高效
开发语言·leetcode·swift
福大大架构师每日一题4 小时前
go 1.25.1发布:重点修复net/http跨域保护安全漏洞(CVE-2025-47910)
开发语言·http·golang
Dear.爬虫5 小时前
Golang中逃逸现象, 变量“何时栈?何时堆?”
开发语言·后端·golang
小刘的AI小站5 小时前
leetcode hot100 二叉搜索树
算法·leetcode
自信的小螺丝钉5 小时前
Leetcode 876. 链表的中间结点 快慢指针
算法·leetcode·链表·指针
红豆怪怪5 小时前
[LeetCode 热题 100] 32. 最长有效括号
数据结构·python·算法·leetcode·动态规划·代理模式