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
}
相关推荐
POLITE38 小时前
Leetcode 437. 路径总和 III (Day 16)JavaScript
javascript·算法·leetcode
历程里程碑9 小时前
双指针2--盛水最多的容器
大数据·数据结构·算法·leetcode·elasticsearch·搜索引擎·散列表
June bug10 小时前
(#数组/链表操作)寻找两个正序数组的中位数
数据结构·python·算法·leetcode·面试·职场和发展·跳槽
TracyCoder12310 小时前
LeetCode Hot100(8/100)—— 438. 找到字符串中所有字母异位词
算法·leetcode
June bug11 小时前
(#数组/链表操作)最长上升子序列的长度
数据结构·程序人生·leetcode·链表·面试·职场和发展·跳槽
hadage23311 小时前
--- 力扣oj柱状图中最大的矩形 单调栈 ---
算法·leetcode·职场和发展
json{shen:"jing"}11 小时前
18. 四数之和
数据结构·算法·leetcode
多米Domi01111 小时前
0x3f 第42天 复习 10:39-11:33
算法·leetcode
议题一玩到11 小时前
#leetcode# 1984. Minimum Difference Between Highest and Lowest of K Scores
数据结构·算法·leetcode
漫随流水12 小时前
leetcode回溯算法(90.子集Ⅱ)
数据结构·算法·leetcode·回溯算法