Leetcode 457 Solution

This article provides solution to leetcode question 457 (circular-array-loop)

https://leetcode.com/problems/circular-array-loop

Solution

class Solution { vector<int>* pnums; public: int next(int i) { return (i + (*pnums)[i] + (*pnums).size()) % (*pnums).size(); }
bool circularArrayLoop(vector<int>& nums) { if (nums.size() == 0) return false;
pnums = &nums;
for (int i = 0; i < nums.size(); i++) { if (nums[i] == 0) continue;
int slow = i; int fast = i;
while (nums[fast] * nums[next(fast)] > 0 && nums[next(fast)] * nums[next(next(fast))] > 0) { slow = next(slow); fast = next(next(fast));
if (slow == fast) { if (slow == next(slow)) break;
printf("%d\n", slow); return true; } }
slow = i; while (nums[i] * nums[next(i)] > 0) { nums[i] = 0; i = next(i); } }
return false; } };