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
}
相关推荐
creator_Li5 小时前
Golang的Map
golang
紫陌涵光7 小时前
669. 修剪二叉搜索树
算法·leetcode
紫陌涵光9 小时前
108.将有序数组转换为二叉搜索树
数据结构·算法·leetcode
iAkuya9 小时前
(leetcode)力扣100 75前K个高频元素(堆)
java·算法·leetcode
creator_Li10 小时前
Golang的切片Slice
golang·slice
美好的事情能不能发生在我身上11 小时前
Leetcode热题100中的:哈希专题
算法·leetcode·哈希算法
逆境不可逃11 小时前
LeetCode 热题 100 之 41.缺失的第一个正数
算法·leetcode·职场和发展
We་ct13 小时前
LeetCode 173. 二叉搜索树迭代器:BSTIterator类 实现与解析
前端·算法·leetcode·typescript
踩坑记录14 小时前
leetcode hot100 79. 单词搜索 medium 递归回溯
leetcode
Rhystt15 小时前
代码随想录第二十六天|669. 修剪二叉搜索树、108.将有序数组转换为二叉搜索树、538.把二叉搜索树转换为累加树
数据结构·c++·算法·leetcode