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
}
相关推荐
未知陨落8 分钟前
LeetCode:95.编辑距离
算法·leetcode
名誉寒冰3 小时前
【LeetCode】454. 四数相加 II 【分组+哈希表】详解
算法·leetcode·散列表
tao3556674 小时前
【Python刷力扣hot100】49. Group Anagrams
开发语言·python·leetcode
夏鹏今天学习了吗5 小时前
【LeetCode热题100(35/100)】LRU 缓存
算法·leetcode·缓存
Q741_1477 小时前
C++ 位运算 高频面试考点 力扣137. 只出现一次的数字 II 题解 每日一题
c++·算法·leetcode·面试·位运算
墨染点香8 小时前
LeetCode 刷题【103. 二叉树的锯齿形层序遍历、104. 二叉树的最大深度、105. 从前序与中序遍历序列构造二叉树】
算法·leetcode·职场和发展
sitellla9 小时前
Testify Go测试工具包入门教程
git·测试工具·其他·golang
Brookty9 小时前
【算法】二分查找(一)朴素二分
java·学习·算法·leetcode·二分查找
黑色的山岗在沉睡10 小时前
LeetCode 2761. 和等于目标值的质数对
算法·leetcode·职场和发展
T1an-114 小时前
力扣70.爬楼梯
算法·leetcode·职场和发展