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
}
相关推荐
Tisfy6 分钟前
LeetCode 3871.统计范围内的逗号 II:每次算一个逗号
数学·算法·leetcode·题解
find1star41 分钟前
LeetCode 54:螺旋矩阵——用四个边界模拟矩阵收缩
java·算法·leetcode·边缘计算·学习方法
吞下星星的少年·-·1 小时前
LeetCode 热题 100 两数之和(哈希表)
算法·leetcode·哈希算法
FfHUCisI1 小时前
Go 内存分配器概览:从 TCMalloc 到三级缓存架构
缓存·架构·golang
土司大王2 小时前
LeetCode hot100——全排列
java·算法·leetcode
203号居民2 小时前
LeetCode hot 100 — 138. 随机链表的复制
算法·leetcode·链表
Johnston_man2 小时前
golang 安装 protoc、protoc-gen-go、protoc-gen-go-grpc、protoc-gen-grpc-gateway
后端·golang
ttwuai2 小时前
Go 后台接入单点登录后,JWT、菜单权限和接口 403 怎么验?
开发语言·后端·golang
土司大王3 小时前
LeetCode hot100——实现 Trie (前缀树)
java·算法·leetcode
麻瓜code4 小时前
【LeetCode】相交链表:双指针法,一次遍历找到交点
算法·leetcode·链表