[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;
    }
};

相关推荐

  1. SQL查询数据是否存在

    2024-07-11 05:48:02       53 阅读
  2. Oracle数组循环存在则删除

    2024-07-11 05:48:02       61 阅读
  3. 在 Python 中编写循环Loops的艺术

    2024-07-11 05:48:02       57 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 05:48:02       53 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 05:48:02       55 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 05:48:02       46 阅读
  4. Python语言-面向对象

    2024-07-11 05:48:02       56 阅读

热门阅读

  1. vite搭建vue2项目

    2024-07-11 05:48:02       19 阅读
  2. 基于STM32设计的智能手环(ESP8266+华为云IOT)178

    2024-07-11 05:48:02       21 阅读
  3. 代码优化(2)——小程序登录

    2024-07-11 05:48:02       22 阅读
  4. LeetCode 981, 219, 78

    2024-07-11 05:48:02       23 阅读
  5. linux中的僵尸进程

    2024-07-11 05:48:02       16 阅读
  6. 保持边界感

    2024-07-11 05:48:02       21 阅读
  7. STM32空闲中断处理串口接受数据

    2024-07-11 05:48:02       20 阅读
  8. GPT-5:探索NLP新纪元的无限可能

    2024-07-11 05:48:02       18 阅读