[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;
    }
};
相关推荐
Ivanqhz39 分钟前
php8 use-def链
算法·php
spter。1 小时前
AI 面试相同请求为什么会重复调用,如何解决
人工智能·面试·职场和发展
evans在进步1 小时前
LeetCode 189 轮转数组:三次反转原地解决,图解 Java 实现
java·算法·leetcode
歌_顿1 小时前
Drawing_To_Model
算法
龍德明宇1 小时前
AI不会疼-龍德明宇
人工智能·算法·大语言模型llm·负主体性·ai存在论
302wanger2 小时前
程序员写 SOP:把脑子里的流程固化下来
算法
科学实验家2 小时前
完全背包
算法
Smoothcloud润云2 小时前
GPU租赁数据安全怎么做?
人工智能·算法·ai·aigc·gpu算力·gpu
呜喵王阿尔萨斯2 小时前
extern “C“ in C++
c语言·c++·算法