One pass O(n) time with O(1) space c++


  • 0
    T

    class Solution {
    public:
    bool circularArrayLoop(vector<int>& nums) {
    if(nums.empty()) {
    return false;
    }
    for(int i=0;i<nums.size();i++) {
    if(nums[i]==0) {
    continue;
    }
    int move = nums[i] > 0 ? 1 : -1;
    int count = 0;
    int k = i;
    while(nums[k]!=0 && move*nums[k]>0) {
    count++;
    int tmp = nums[k];
    nums[k] = 0;
    k = (k+tmp)% nums.size();
    }
    if(count>1 && nums[k]==0) {
    return true;
    }
    }
    return false;
    }
    };


Log in to reply
 

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