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 小时前
leetcode 3418. 机器人可以获得的最大金币数 中等
leetcode
cch89184 小时前
汇编与Go:底层到高层的编程差异
java·汇编·golang
_日拱一卒7 小时前
LeetCode:最大子数组和
数据结构·算法·leetcode
小辉同志9 小时前
78. 子集
算法·leetcode·深度优先
白毛大侠10 小时前
Go Goroutine 与用户态是进程级
开发语言·后端·golang
Demon--hx12 小时前
[LeetCode]100 链表-专题
算法·leetcode·链表
_深海凉_12 小时前
LeetCode热题100-LRU 缓存
算法·leetcode·缓存
lolo大魔王13 小时前
Go语言的基础语法
开发语言·后端·golang
liuyao_xianhui13 小时前
优选算法_岛屿的最大面积_floodfill算法_C++
java·开发语言·数据结构·c++·算法·leetcode·链表