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
}
相关推荐
想吃火锅10058 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
Nil2089 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
朋克洛德的码农12 小时前
Go并发-sync包四剑客:Mutex、RWMutex、WaitGroup、Once-从入门到原理
开发语言·后端·golang
圣殿骑士-Khtangc12 小时前
Go泛型编程实战从类型约束到泛型数据结构
golang
evans在进步14 小时前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode
Nil20814 小时前
leetcode 189轮转数组
数据结构·算法·leetcode
FfHUCisI14 小时前
Golang - 信号量模式(Semaphore Pattern)
开发语言·后端·golang
吃着火锅x唱着歌15 小时前
LeetCode 3885.设计事件管理器
算法·leetcode·职场和发展
土司大王15 小时前
LeetCode hto100——字母异位词分组
java·算法·leetcode
土司大王16 小时前
LeetCode hot100——两数之和
数据结构·算法·leetcode