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
}
相关推荐
卜锦元25 分钟前
Go中使用wire进行统一依赖注入管理
开发语言·后端·golang
mit6.8245 小时前
论容器化 | 分析Go和Rust做医疗的后端服务
docker·golang·rust
ykuaile_h86 小时前
Go 编译报错排查:vendor/golang.org/x/crypto/cryptobyte/asn1 no Go source files
后端·golang
科大饭桶6 小时前
数据结构自学Day5--链表知识总结
数据结构·算法·leetcode·链表·c
YuTaoShao8 小时前
【LeetCode 热题 100】24. 两两交换链表中的节点——(解法一)迭代+哨兵
java·算法·leetcode·链表
前端拿破轮9 小时前
翻转字符串里的单词,难点不是翻转,而是正则表达式?💩💩💩
算法·leetcode·面试
凤年徐9 小时前
【数据结构与算法】203.移除链表元素(LeetCode)图文详解
c语言·开发语言·数据结构·算法·leetcode·链表·刷题
李昊_10 小时前
【LeetCode 3440. 重新安排会议得到最多空余时间 II】解析
算法·leetcode
呆呆的小鳄鱼10 小时前
leetcode:322. 零钱兑换[完全背包]
算法·leetcode·职场和发展
এ᭄画画的北北11 小时前
力扣-240.搜索二维矩阵 II
算法·leetcode·矩阵