美文网首页
(判环)457. 环形数组是否存在循环

(判环)457. 环形数组是否存在循环

作者: 来到了没有知识的荒原 | 来源:发表于2021-08-07 11:28 被阅读0次

    457. 环形数组是否存在循环

    class Solution {
     public:
      bool circularArrayLoop(vector<int>& nums) {
        int n = nums.size();
        auto next = [&](int x) { return ((x + nums[x]) % n + n) % n; };
    
        for (int i = 0; i < n; i++) {
          int slow = i, fast = next(i);
          if (!nums[slow]) continue;
          if (nums[slow] * nums[fast] <= 0) continue;
          while (nums[fast] * nums[next(fast)] > 0) {
            if (!nums[slow]) break;
            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 t = add;
            add = next(add);
            nums[t] = 0;
          }
        }
        return false;
      }
    };
    

    相关文章

      网友评论

          本文标题:(判环)457. 环形数组是否存在循环

          本文链接:https://www.haomeiwen.com/subject/zmwwvltx.html