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
}
相关推荐
姚不倒3 小时前
Go语言进阶:接口、错误处理与并发编程(goroutine/channel/context)
云原生·golang
失去的青春---夕阳下的奔跑6 小时前
560. 和为 K 的子数组
数据结构·算法·leetcode
m0_629494737 小时前
LeetCode 热题 100-----25.回文链表
数据结构·算法·leetcode·链表
吃着火锅x唱着歌9 小时前
LeetCode 1019.链表中的下一个更大节点
算法·leetcode·链表
凌波粒10 小时前
LeetCode--404.左叶子之和(二叉树)
算法·leetcode·职场和发展
绝知此事10 小时前
【算法突围 03】核心算法思想:分治/递归/动态规划与 LeetCode 高频真题解析
算法·leetcode·面试·动态规划
宇明一不急10 小时前
go 链表 (标准库实现)
开发语言·链表·golang
阿Y加油吧12 小时前
两道字符串 DP 模板题复盘:最长公共子序列 & 编辑距离
leetcode
~|Bernard|12 小时前
GO语言中哪些类型是可比较类型的(==和!=)
开发语言·后端·golang
我爱cope12 小时前
【力扣hot100:76. 最小覆盖子串】
算法·leetcode·职场和发展