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 小时前
LeetCode 热题 100——哈希——最长连续序列
算法·leetcode·哈希算法
Dream it possible!2 小时前
LeetCode 面试经典 150_二叉树_二叉树展开为链表(74_114_C++_中等)
c++·leetcode·链表·面试·二叉树
做怪小疯子2 小时前
LeetCode 热题 100——双指针——三数之和
算法·leetcode·职场和发展
sin_hielo2 小时前
leetcode 2536
数据结构·算法·leetcode
flashlight_hi2 小时前
LeetCode 分类刷题:203. 移除链表元素
算法·leetcode·链表
py有趣2 小时前
LeetCode算法学习之数组中的第K个最大元素
学习·算法·leetcode
吗~喽2 小时前
【LeetCode】将 x 减到 0 的最小操作数
算法·leetcode
stand_forever4 小时前
PHP客户端调用由Go服务端GRPC接口
rpc·golang·php
flashlight_hi6 小时前
LeetCode 分类刷题:3217. 从链表中移除在数组中存在的节点
javascript·数据结构·leetcode·链表
Tisfy6 小时前
LeetCode 2536.子矩阵元素加 1:二维差分数组
算法·leetcode·矩阵