[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;
    }
};
相关推荐
zxsz_com_cn8 分钟前
设备预测性维护算法核心功能有哪些?六大模块拆解智能运维的“技术骨架”
运维·算法
期末考复习中,蓝桥杯都没时间学了10 分钟前
力扣刷题13
数据结构·算法·leetcode
2201_7569890920 分钟前
C++中的事件驱动编程
开发语言·c++·算法
会飞的战斗鸡25 分钟前
JS中的链表(含leetcode例题)
javascript·leetcode·链表
多米Domi01131 分钟前
0x3f 第48天 面向实习的八股背诵第五天 + 堆一题 背了JUC的题,java.util.Concurrency
开发语言·数据结构·python·算法·leetcode·面试
2301_8223776532 分钟前
模板元编程调试方法
开发语言·c++·算法
故以往之不谏1 小时前
函数--值传递
开发语言·数据结构·c++·算法·学习方法
渐暖°1 小时前
【leetcode算法从入门到精通】5. 最长回文子串
vscode·算法·leetcode
今天_也很困1 小时前
LeetCode热题100-560. 和为 K 的子数组
java·算法·leetcode
v_for_van1 小时前
力扣刷题记录2(无算法背景,纯C语言)
c语言·算法·leetcode