[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;
    }
};
相关推荐
wuhen_n5 分钟前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo12 分钟前
leetcode 2483
数据结构·算法·leetcode
Xの哲學1 小时前
Linux多级时间轮:高精度定时器的艺术与科学
linux·服务器·网络·算法·边缘计算
大头流矢1 小时前
归并排序与计数排序详解
数据结构·算法·排序算法
油泼辣子多加1 小时前
【信创】算法开发适配
人工智能·深度学习·算法·机器学习
Aaron15882 小时前
AD9084和Versal RF系列具体应用案例对比分析
嵌入式硬件·算法·fpga开发·硬件架构·硬件工程·信号处理·基带工程
laocooon5238578862 小时前
插入法排序 python
开发语言·python·算法
wuhen_n3 小时前
LeetCode -- 1:两数之和(简单)
javascript·算法·leetcode·职场和发展
林shir4 小时前
Java基础1.7-数组
java·算法
Jeremy爱编码4 小时前
leetcode课程表
算法·leetcode·职场和发展