simple c++ solution with marker time O(n) space O(1)


  • 1
    O

    class Solution {
    public:
    bool circularArrayLoop(vector<int>& nums) {
    int next = 0;
    if(nums.size() == 0)
    return 0;
    while(1){
    int step = nums[next];
    nums[next] = 0;
    if(step > 0) {
    next = (next + step) % nums.size();
    } else if(step == 0) {
    return false;
    } else {
    next = nums.size() - (abs(next + step) % nums.size());
    }
    if(next == nums.size() - 1)
    return false;
    if(nums[next] == 0)
    return true;
    }

        return false;
    }
    

    };


  • 1
    O

    reformat

    class Solution {
    public:
        bool circularArrayLoop(vector<int>& nums) {
            int next = 0;
            if(nums.size() == 0)
                return 0;
            while(1){
                int step = nums[next];
                nums[next] = 0;
                if(step > 0) {
                    next = (next + step) % nums.size();
                } else if(step == 0) {
                    return false;
                } else {
                    next = nums.size() - (abs(next + step) % nums.size());
                }
                if(next == nums.size() - 1)
                    return false;
                if(nums[next] == 0)
                    return true;
            }
            
            return false;
        }
    };
    

  • 0
    K

    @orion.zhangle The code is wrong. Please check it with this test case : [-1, -1, -1]


Log in to reply
 

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