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
}
相关推荐
夜斗小神社5 小时前
【LeetCode 热题 100】(六)矩阵
算法·leetcode·矩阵
花酒锄作田6 小时前
[Python][Go]比较两个JSON文件之间的差异
python·golang
阿狗哲哲9 小时前
Java选手如何看待Golang
java·开发语言·golang
zxctsclrjjjcph18 小时前
【递归、搜索和回溯】FloodFill 算法介绍及相关例题
c++·算法·leetcode·宽度优先·深度优先遍历
Runing_WoNiu20 小时前
Golang 与Java 单例模式、工厂模式比较
java·单例模式·golang
胡萝卜的兔21 小时前
go语言标准库学习, fmt标准输出,Time 时间,Flag,Log日志,Strconv
开发语言·学习·golang
adminwolf1 天前
基于Vue.js和Golang构建高效在线客服系统:前端实现与后端交互详解
前端·vue.js·golang
崎岖Qiu1 天前
leetcode1343:大小为K的子数组(定长滑动窗口)
java·算法·leetcode·力扣·滑动窗口
zhoupenghui1681 天前
golang实现支持100万个并发连接(例如,HTTP长连接或WebSocket连接)系统架构设计详解
开发语言·后端·websocket·golang·系统架构·echo·100万并发
Dream it possible!2 天前
LeetCode 面试经典 150_数组/字符串_加油站(14_134_C++_中等)(贪心算法)
c++·leetcode·面试