457. Circular Array Loop

You are given an array of positive and negative integers. If a number n at an index is positive, then move forward n steps. Conversely, if it's negative (-n), move backward n steps. Assume the first element of the array is forward next to the last element, and the last element is backward next to the first element. Determine if there is a loop in this array. A loop starts and ends at a particular index with more than 1 element along the loop. The loop must be "forward" or "backward'.

Example 1: Given the array [2, -1, 1, 2, 2], there is a loop, from index 0 -> 2 -> 3 -> 0.

Example 2: Given the array [-1, 2], there is no loop.

Note: The given array is guaranteed to contain no element "0".

Can you do it in O(n) time complexity and O(1) space complexit

快慢指针,类似判断链表是否有环的方法,程序如下所示:

class Solution {
    public boolean circularArrayLoop(int[] nums) {
        int n = nums.length;
        if (n <= 1){
            return false;
        }
        for (int i = 0; i < n; i++) {
            int j = i, k = getNext(i, nums);
            while (nums[k] * nums[i] > 0 && nums[j] * nums[i] > 0) {
                if (j == k) {
                    if (j == getNext(j, nums)){
                        break;
                    }
                    return true;
                }
                j = getNext(j, nums);
                k = getNext(k, nums);
                if (nums[k] * nums[i] < 0) {
                    break;
                }
                k = getNext(k, nums);
            }
        }
        return false;
    }
    public int getNext(int i, int[] nums){
        return (i + nums[i] + nums.length)%nums.length;
    }
}

猜你喜欢

转载自blog.csdn.net/excellentlizhensbfhw/article/details/81151011