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
}
相关推荐
运筹vivo@8 小时前
2657. 找到两个数组的前缀公共数组 | 难度:中等
算法·leetcode·职场和发展·哈希表
比特森林探险记8 小时前
go 语言中的context 解读和用法
开发语言·后端·golang
叶小鸡14 小时前
小鸡玩算法-力扣HOT100-动态规划(下)
算法·leetcode·动态规划
毅炼16 小时前
今日LeetCode 摸鱼打卡
java·算法·leetcode
m0_6294947316 小时前
LeetCode 热题 100-----28. 两数相加
数据结构·算法·leetcode·链表
菜菜的顾清寒16 小时前
力扣HOT100(25)环形链表
算法·leetcode·链表
jieyucx18 小时前
从基础语法到面向对象:Go语言如何实现封装、继承与多态?
开发语言·后端·golang
littleschemer19 小时前
Go:实现游戏服务器网关
服务器·网关·游戏·golang
Controller-Inversion20 小时前
76. 最小覆盖子串
java·算法·leetcode
_日拱一卒20 小时前
LeetCode:437路径总和Ⅲ
算法·leetcode·职场和发展