leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0457.cpp (905B)
0 class Solution { 1 public: 2 bool circularArrayLoop(vector<int> &nums) const { 3 const int n = size(nums); 4 static int seen[5001]; 5 6 const auto next = [&](int k) { 7 const int res = (k + nums[k] % n + n) % n; 8 seen[res] = true; 9 return res; 10 }; 11 12 memset(seen, 0x00, sizeof(seen)); 13 for (auto &num : nums) 14 num %= n; 15 16 for (int i = 0; i < n; i++) { 17 if (seen[i]) continue; 18 int t = i, h = i; 19 20 do { 21 t = next(t); 22 h = next(next(h)); 23 } while (t != h); 24 25 const bool dir = nums[t] > 0; 26 do { 27 t = next(t); 28 if ((nums[t] > 0) != dir) goto next; 29 } while (t != h); 30 31 if ((t + nums[t] + n) % n != t) return true; 32 next:; 33 } 34 35 return false; 36 } 37 };