leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0457.cpp (905B)


      1 class Solution {
      2   public:
      3     bool circularArrayLoop(vector<int> &nums) const {
      4         const int n = size(nums);
      5         static int seen[5001];
      6 
      7         const auto next = [&](int k) {
      8             const int res = (k + nums[k] % n + n) % n;
      9             seen[res] = true;
     10             return res;
     11         };
     12 
     13         memset(seen, 0x00, sizeof(seen));
     14         for (auto &num : nums)
     15             num %= n;
     16 
     17         for (int i = 0; i < n; i++) {
     18             if (seen[i]) continue;
     19             int t = i, h = i;
     20 
     21             do {
     22                 t = next(t);
     23                 h = next(next(h));
     24             } while (t != h);
     25 
     26             const bool dir = nums[t] > 0;
     27             do {
     28                 t = next(t);
     29                 if ((nums[t] > 0) != dir) goto next;
     30             } while (t != h);
     31 
     32             if ((t + nums[t] + n) % n != t) return true;
     33         next:;
     34         }
     35 
     36         return false;
     37     }
     38 };