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
}
相关推荐
smj2302_796826529 小时前
解决leetcode第3943题递增后的数对数量
数据结构·python·算法·leetcode
姚不倒11 小时前
从零实现一个基于 Ollama + Go + MySQL 的 Text-to-SQL 智能体(M1 实战)
sql·mysql·云原生·golang
医用门11 小时前
医院用门一线品牌
leetcode
he___H13 小时前
leetcode100-普通数组
java·数据结构·算法·leetcode
菜菜的顾清寒16 小时前
力扣HOT100(30)两两交换链表中的节点
算法·leetcode·链表
csdn_aspnet18 小时前
C++ 算法 LeetCode 编号 70 - 爬楼梯
开发语言·c++·算法·leetcode
圣保罗的大教堂18 小时前
leetcode 2770. 达到末尾下标所需的最大跳跃次数 中等
leetcode
wlsh1519 小时前
Go 泛型笔记
golang
姚不倒19 小时前
从「LeetCode LRU 缓存」到「生产级 Go Web 服务」:我如何迈出工程化第一步
leetcode·缓存·云原生·golang
sheeta199819 小时前
LeetCode 每日一题笔记 日期:2026.05.25 题目:1871. 跳跃游戏 VII
笔记·leetcode·游戏