[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;
    }
};
相关推荐
hk112432 分钟前
【NLP/PatternRec】2026年度语义鸿沟分析与模糊模式识别基准索引 (Benchmark Index)
算法·自然语言处理·数据集·知识图谱·模式识别
hetao173383734 分钟前
2025-12-31~2026-1-2 hetao1733837 的刷题笔记
c++·笔记·算法
yyy(十一月限定版)1 小时前
算法——差分
算法
yyy(十一月限定版)1 小时前
算法——模拟
算法
DeepVis Research1 小时前
【Chaos/Neuro】2026年度混沌动力学仿真与机器遗忘算法基准索引 (Benchmark Index)
人工智能·算法·数据集·混沌工程·高性能计算
一起养小猫1 小时前
LeetCode100天Day9-无重复字符的最长子串与赎金信
java·开发语言·数据结构·leetcode
white-persist1 小时前
【内网运维】Netstat与Wireshark:内网运维溯源实战解析
运维·网络·数据结构·测试工具·算法·网络安全·wireshark
会员果汁1 小时前
7.设计模式-模板方法模式
算法·设计模式·模板方法模式
努力学算法的蒟蒻1 小时前
day52(1.2)——leetcode面试经典150
算法·leetcode·面试
java修仙传1 小时前
力扣hot100:字符串解码
算法·leetcode·职场和发展