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'.oop

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

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

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

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

 

解题思路:ci

首先咱们要明确怎样算是一个环:element

  1. 起始坐标和结束坐标为同一坐标get

  2. 环中要有多于一个的元素it

  3. 环须要是单向的。即要么只向前,要么只向后。

首先根据题意咱们能够构造一个辅助方法:getNextIdx,找该点下个点。

这里须要注意的是!

数组中存在的环的起始点不定,因此咱们要对每个点为起始点存在的环来进行判断。

 

代码:

class Solution {
public:
    bool circularArrayLoop(vector<int>& nums) {
        if(nums.size() == 0) return false;
        for(int i = 0; i < nums.size(); i++){
            if(isLoop(nums, i)) return true;
        }
        return false;
    }
    int getNextIdx(vector<int>& nums, int cur){
        int len = nums.size();
        cur = cur + nums[cur];
        if(cur > 0) cur = cur % len;
        else cur = len - abs(cur)%len;
        return cur;
    }
    bool isLoop(vector<int> nums, int i){
        int slow = i, fast = i;
        int len = nums.size();
        do{
            slow = getNextIdx(nums, slow);
            fast = getNextIdx(nums, fast);
            fast = getNextIdx(nums, fast);
        }while(slow != fast);
        int nxt = getNextIdx(nums, slow);
        if(nxt == slow) return false;
        int direction = nums[fast] / abs(nums[fast]);
        int start = fast;
        do{
            if(nums[start] * direction < 0) return false;
            start = getNextIdx(nums, start);
        }while(start != fast);
        
        return true;
    }
};
相关文章
相关标签/搜索