(判环)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
网友评论