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
}
相关推荐
Navigator_Z6 小时前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
lvwangshu7 小时前
登录日志 题解
数据结构·线段树·题解·技巧·性质题·思维好题·细节题
青山木9 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
All for pursuit.12 小时前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
大侠归来15 小时前
C 与 Go 语言对比:从设计哲学到工程实践
java·c语言·golang
All for pursuit.15 小时前
【回溯-5】78.子集
数据结构·c++·算法·leetcode
小小龙学IT16 小时前
Go 语言内存管理与垃圾回收(GC)深度解析:从逃逸分析到性能调优适
golang·go1.19
漂流瓶jz17 小时前
UVA-1610 聚会游戏 题解答案代码 算法竞赛入门经典第二版
数据结构·c++·算法·题解·aoapc·算法竞赛入门经典·uva
代码什么用17 小时前
LeetCode-560.和为 K 的子数组
算法·leetcode
All for pursuit.17 小时前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode