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
}
相关推荐
暖阳华笺17 分钟前
【数据结构与算法】哈希专题
数据结构·c++·算法·leetcode·哈希算法
AKA__Zas29 分钟前
芝士算法(滑动窗口片 2.0)
java·算法·leetcode·学习方法
四代水门41 分钟前
LeetCode刷算法题(C++)
c++·算法·leetcode
退休倒计时12 小时前
【每日一题】LeetCode 53. 最大子数组和 TypeScript
数据结构·算法·leetcode·typescript
张忠琳14 小时前
【Go 1.26.4】Golang Channel 深度解析
开发语言·后端·golang
洛水水15 小时前
【力扣100题】86.柱状图中最大的矩形
算法·leetcode·职场和发展
洛水水16 小时前
【力扣100题】81.寻找两个正序数组的中位数
数据结构·算法·leetcode
张忠琳16 小时前
【Go 1.26.4】Golang Map 深度解析
开发语言·后端·golang
洛水水17 小时前
【力扣100题】85.每日温度
算法·leetcode·职场和发展
Kurisu_红莉栖17 小时前
力扣56合并区间
算法·leetcode