[leetcode]circular-array-loop 环形数组是否存在循环

. - 力扣(LeetCode)

复制代码
class Solution {
public:
    bool circularArrayLoop(vector<int>& nums) {
        int n = nums.size();
        auto next = [&](int cur) {
            return ((cur + nums[cur]) % n + n) % n; // 保证返回值在 [0,n) 中
        };

        for (int i = 0; i < n; i++) {
            if (!nums[i]) {
                continue;
            }
            int slow = i, fast = next(i);
            // 判断非零且方向相同
            while (nums[slow] * nums[fast] > 0 && nums[slow] * nums[next(fast)] > 0) {
                if (slow == fast) {
                    if (slow != next(slow)) {
                        return true;
                    } else {
                        break;
                    }
                }
                slow = next(slow);
                fast = next(next(fast));
            }
            int add = i;
            while (nums[add] * nums[next(add)] > 0) {
                int tmp = add;
                add = next(add);
                nums[tmp] = 0;
            }
        }
        return false;
    }
};
相关推荐
写写闲篇儿2 小时前
下一个更大元素(一)
数据结构·算法
MobotStone4 小时前
从金鱼记忆到过目不忘:Transformer 如何让AI真正理解一句话?
算法
炽烈小老头5 小时前
【每天学习一点算法 2025/12/19】二叉树的层序遍历
数据结构·学习·算法
Xの哲學5 小时前
Linux grep命令:文本搜索的艺术与科学
linux·服务器·算法·架构·边缘计算
soft20015256 小时前
MySQL Buffer Pool深度解析:LRU算法的完美与缺陷
数据库·mysql·算法
WBluuue6 小时前
AtCoder Beginner Contest 436(ABCDEF)
c++·算法
fie88896 小时前
广义 S 变换(GST)地震信号时频谱
算法
json{shen:"jing"}7 小时前
1-C语言的数据类型
c语言·c++·算法
im_AMBER7 小时前
数据结构 13 图 | 哈希表 | 树
数据结构·笔记·学习·算法·散列表
LYFlied7 小时前
【算法解题模板】动态规划:从暴力递归到优雅状态转移的进阶之路
数据结构·算法·leetcode·面试·动态规划