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
}
相关推荐
203号居民11 小时前
LeetCode hot 100 —41. 缺失的第一个正数
数据结构·算法·leetcode
evans在进步13 小时前
LeetCode 322:零钱兑换——Java 动态规划详解
java·leetcode·动态规划
Tisfy15 小时前
LeetCode 3471.找出最大的几近缺失整数:三种情况判断
算法·leetcode·题解·分类讨论
码农大叔的博客18 小时前
golang示例:switch
开发语言·后端·golang
青 春 记 忆19 小时前
LeetCode 121. 买卖股票的最佳时机|Python 解法详解
python·算法·leetcode
rannn_11119 小时前
【力扣hot100】二叉树专题
算法·leetcode·职场和发展
圣殿骑士-Khtangc20 小时前
Go面试核心考点之GMP调度器源码级深度解析
golang
Navigator_Z21 小时前
LeetCode //C - 1203. Sort Items by Groups Respecting Dependencies
c语言·算法·leetcode
Scabbards_1 天前
面试Leetcode - Heap 堆
java·leetcode·面试
ValhallaCoder2 天前
Leetcode-hot100(2026.08.17)
python·算法·leetcode