modify the input array to so visited index can be marked.


  • 0
    C
    public class Solution {
        public boolean circularArrayLoop(int[] nums) {
            if (nums == null || nums.length <= 1) {
                return false;
            }
            int start = 0,iteration = 0, firstElement = 0, firstIndex = 0, temp = 0;
            while (iteration < nums.length) {
                // start from a new index in each iteration
                for (int i = iteration ; i < nums.length; ++i) {
                    if (nums[i] != 0) {
                        start = i;
                        break;
                    }
                }
                
                iteration = start + 1;
                firstIndex = start;
                if (nums[start] == 0) {
                    continue;
                }            
                temp = nums[start];
                boolean isForward = (temp > 0 ? true : false);
                nums[start] = 0;
                start = (start + temp + nums.length) % nums.length;
                int len = 1;
                
                while (nums[start] != 0 && start != firstIndex) {
                    temp = nums[start];
                    boolean currentIsForward = (temp > 0 ? true : false);
                    // should be in the same direction
                    if (currentIsForward != isForward) { 
                        break;
                    }
                    nums[start] = 0;
                    start = (start + temp + nums.length) % nums.length;
                    ++len;
                }
                // 1 should be at least 2 in length.
                // 2 compapre index instead of value, since value is modified.
                if (len != 1 && start == firstIndex) { 
                    return true;
                }
            }
            return false;
        }
    }
    

Log in to reply
 

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