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
}
相关推荐
he___H5 小时前
接雨水----解
leetcode
洛水水7 小时前
【力扣100题】23. 螺旋矩阵
算法·leetcode·矩阵
~|Bernard|10 小时前
四,go语言中GMP调度模型
java·前端·golang
Tisfy10 小时前
LeetCode 2553.分割数组中数字的数位:模拟(maybe+翻转)——java也O(1)
java·数学·算法·leetcode·题解·模拟·取模
Controller-Inversion10 小时前
42. 接雨水
数据结构·算法·leetcode
Controller-Inversion10 小时前
33. 搜索旋转排序数组
数据结构·算法·leetcode
驼同学.10 小时前
【求职季】LeetCode Hot 100 渐进式扫盲手册(Python版)
python·算法·leetcode
宵时待雨11 小时前
优选算法专题6:模拟
数据结构·c++·算法·leetcode·职场和发展
Liangwei Lin11 小时前
LeetCode 35. 搜索插入位置
数据结构·算法·leetcode
littleschemer12 小时前
Go 手动挡元编程:go:generate 实战解析
golang·游戏服务器·元编程·generate