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
}
相关推荐
hanlin035 小时前
刷题笔记:力扣第32题-最长有效括号
笔记·算法·leetcode
All for pursuit.6 小时前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划
Scintilla_y9 小时前
DAY2 滑动窗口
算法·leetcode·散列表
特立独行的猫a10 小时前
仓颉语言UI开发实战:我用仓颉写了个桌面版力扣
算法·leetcode·ui·tauri·仓颉·cj-tarui
茉莉玫瑰花茶10 小时前
GO [ 标准库 ]
开发语言·后端·golang
y1su10 小时前
Leetcode 动态规划 模板
java·数据结构·算法·leetcode·动态规划
All for pursuit.11 小时前
【位运算-3】136.只出现一次的数字
数据结构·c++·算法·leetcode
All for pursuit.13 小时前
【完结】LeetCodeHot100题 详细解题过程及代码汇总
数据结构·c++·算法·leetcode
mmmmath_313 小时前
LeetCode.101.对称二叉树
数据结构·leetcode
mmmmath_318 小时前
LeetCode.637.二叉树的层平均值
算法·leetcode