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
}
相关推荐
evans在进步6 小时前
LeetCode 64:最小路径和——Java 原地动态规划详解
java·leetcode·动态规划
Tisfy7 小时前
LeetCode 1386.安排电影院座位:哈希表+位运算
算法·leetcode·散列表·题解·哈希表
Nil2087 小时前
leetcode 199二叉树的右视图
算法·leetcode·深度优先
敢敢のwings10 小时前
智元 GO-2 与 AgiBot-World 深度解读
开发语言·后端·golang
FfHUCisI10 小时前
Golang 数据库连接池深度调优
android·数据库·golang
程序员小八77711 小时前
Java 快速转 Go
java·python·golang
土司大王12 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
zander25813 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
欧叶冲冲冲14 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
名字还没想好☜14 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go