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
}
相关推荐
文丑颜不良啊10 小时前
LeetCode1941~1960题目解析
java·leetcode
文丑颜不良啊15 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊15 小时前
LeetCode2001~2020题目解析
java·leetcode
紧跟先前的步伐17 小时前
Go AI Agent 实战 28|Agent 的预算、超时与停止条件
开发语言·人工智能·后端·ai·golang
文丑颜不良啊18 小时前
LeetCode2021~2040题目解析
java·leetcode
利威尔xu1 天前
2026-11-05-Go内存管理面试
面试·golang
Nuanyt1 天前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表
圣保罗的大教堂2 天前
leetcode 3736. 最小操作次数使数组元素相等 III 简单
leetcode
文丑颜不良啊2 天前
LeetCode1881~1990题目解析
java·leetcode