Share my simple AC solution using unordered_set (C++)


  • 0
    S
    class Solution {
    public:
        bool circularArrayLoop(vector<int>& nums) {
            bool forward;
            int size = nums.size();
            for (int i = 0; i < size; i++) {
                 unordered_set<int> appear;
                 forward = (nums[i] > 0);
                 int cur = i;
                 int count = 0;
                 while (true) {
                     if (forward && nums[cur % size] < 0) break;
                     if (!forward) {
                         cur -= (cur / size - 1) * size;
                         if (nums[cur % size] > 0) break;
                     }
                     if (appear.find(cur % size) != appear.end()) break;
                     appear.insert(cur % size);
                     cur += nums[cur % size];
                     count++;
                 }
                 if (cur % size == i) {
                     if (count > 1) return true;
                 }
            }
            return false;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.