JAVA 1ms Accepted code by Mark 0


  • 0
    C

    Basically, use this condition, array contains no element "0"
    Go through nums from 0 to len - 1, in each round, mark every next index to 0 and when it return to itself, return true.

    class Solution {
        public boolean circularArrayLoop(int[] nums) {
            if (nums == null || nums.length == 0) return false;
            int len = nums.length;
            for (int i = 0; i < len; i++) {
                int cur = i;
    // The first few rounds will mark some 0 and since the round goes by, the later round will have less marked 0.
    // and most of them will be triggered by nums[cur] == 0
                if (nums[cur] == 0) continue;
                
                while (nums[cur] != 0) {
    // pay attention to steps, which is the next index, forward or backward.
                    int index =  nums[cur] > 0 ? ((cur + nums[cur]) % len) : (len - Math.abs((cur + nums[cur]) % len)) % len;
                    nums[cur] = 0;
                    cur = index;
                }
                
                if (cur == i) return true;
                
            }
            
            return false;
        }
    }
    

  • 0
    P

    This code is wrong when the test case is [2,2,-1,1].


Log in to reply
 

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