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
}
相关推荐
CoderYanger16 小时前
A.每日一题:输入单词需要的最少按键次数 Ⅰ+Ⅱ
java·数据结构·算法·leetcode·面试
Navigator_Z17 小时前
LeetCode //C - 1221. Split a String in Balanced Strings
c语言·算法·leetcode
2601_9620702319 小时前
差异基因富集分析(R语言——GO&KEGG&GSEA)
开发语言·golang·r语言
「、皓子~20 小时前
海狸IM 2.1 正式发布
flutter·微服务·golang·electron·开源软件·im·海狸im
玄昌盛不会编程20 小时前
LeetCode——2091. 从数组中移除最大值和最小值
java·算法·leetcode
旖旎夜光21 小时前
LeetCode 238:除自身以外数组的乘积(前缀和) —— 题解
数据结构·c++·算法·leetcode·前缀和
运维开发笔记1 天前
8.1 Go Struct 结构体基础
golang
ttwuai1 天前
Go 后台接入 CAS 单点登录后,原来的权限怎么继续生效?
开发语言·后端·golang
学习星球1 天前
单调栈——从“找下一个更大的“到柱状图中的最大矩形
数据库·c++·算法·leetcode·xcode