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
}
相关推荐
卡提西亚1 小时前
leetcode-1438. 绝对差不超过限制的最长连续子数组
算法·leetcode·职场和发展
Java面试题总结1 小时前
LeetCode 93.复原IP地址
算法·leetcode·职场和发展·.net
Frostnova丶7 小时前
(17)LeetCode 41. 缺失的第一个正数
数据结构·算法·leetcode
旖-旎7 小时前
《LeetCode 416 分割等和子集》
c++·算法·leetcode·动态规划·背包问题
geovindu9 小时前
go: Recursion Algorithm
开发语言·后端·算法·golang·递归算法
闪电悠米10 小时前
力扣hot100-53.最大子数组和-动态规划详解
算法·leetcode·动态规划·dp·hot100
Java面试题总结11 小时前
Go 语言大白话入门 6 - 判断与循环
开发语言·后端·golang
techdashen1 天前
Go 1.26 新增 `bytes.Buffer.Peek`:只看数据,不移动读取位置
开发语言·后端·golang
ttwuai1 天前
Go 后台接口 401/403 排查:JWT 过期、刷新请求和权限码怎么定位
开发语言·golang·状态模式
晚笙coding1 天前
LeetCode 226. 翻转二叉树(Invert Binary Tree)
算法·leetcode·职场和发展