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
}
相关推荐
8Qi88 小时前
LeetCode 75:颜色分类(荷兰国旗问题)—— Java 题解 ✅
java·算法·leetcode·指针·排序
codeejun9 小时前
每日一Go-73、云原生成本优化 —— 资源限制 & 指标驱动扩容
开发语言·云原生·golang
(●—●)橘子……11 小时前
力扣第503场周赛练习理解
python·学习·算法·leetcode·职场和发展·周赛
风筝在晴天搁浅14 小时前
快手 CodeTop LeetCode 224.基本计算器
数据结构·算法·leetcode
8Qi816 小时前
LeetCode 31:下一个排列(Next Permutation)—— 完整题解笔记 ✅
笔记·算法·leetcode·指针·思维·排列
玖釉-16 小时前
编辑距离(Edit Distance)——从字符串相似度到动态规划经典模型
算法·leetcode·动态规划
小小龙学IT17 小时前
Go语言后端开发入门指南
开发语言·后端·golang
_日拱一卒17 小时前
LeetCode:46全排列
算法·leetcode·职场和发展
剑挑星河月18 小时前
31.下一个排列
java·算法·leetcode
basketball61618 小时前
Go 语言从入门到进阶:6. 一文彻底吃透结构体(Struct)
开发语言·unity·golang