Tuesday, June 25, 2019

LeetCode [457] Circular Array Loop

You are given a circular array nums of positive and negative integers. If a number kat an index is positive, then move forward k steps. Conversely, if it's negative (-k), move backward k steps. Since the array is circular, you may assume that the last element's next element is the first element, and the first element's previous element is the last element.
Determine if there is a loop (or a cycle) in nums. A cycle must start and end at the same index and the cycle's length > 1. Furthermore, movements in a cycle must all follow a single direction. In other words, a cycle must not consist of both forward and backward movements.

Example 1:
Input: [2,-1,1,2,2]
Output: true
Explanation: There is a cycle, from index 0 -> 2 -> 3 -> 0. The cycle's length is 3.
Example 2:
Input: [-1,2]
Output: false
Explanation: The movement from index 1 -> 1 -> 1 ... is not a cycle, because the cycle's length is 1. By definition the cycle's length must be greater than 1.
Example 3:
Input: [-2,1,-1,-2,-2]
Output: false
Explanation: The movement from index 1 -> 2 -> 1 -> ... is not a cycle, because movement from index 1 -> 2 is a forward movement, but movement from index 2 -> 1 is a backward movement. All movements in a cycle must follow a single direction.

Note:
  1. -1000 ≤ nums[i] ≤ 1000
  2. nums[i] ≠ 0
  3. 1 ≤ nums.length ≤ 5000

Follow up:
Could you solve it in O(n) time complexity and O(1) extra space complexity?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
    int mod(int x, int y){
        if(x%y>=0) return x%y;
        else return x%y+y;
    }
public:
    bool circularArrayLoop(vector<int>& nums) {
        int n = nums.size();
        if(n==0) return false; 

        for(int i=0; i<n; ++i)
        {
            int p1 = i, p2 = i;
            int length = 0;//cycle length;
            while(true){
                length++;
                p1 = mod(p1+nums[p1], n);
                int step1 = nums[p2];
                int step2 = nums[mod(p2+step1, n)];
                p2 = mod(p2+step1+step2, n);
                if(nums[p1]*nums[i]<=0 || nums[p2]*nums[i]<=0 ) break;//wrong direction
                if(p1==p2) break; //because nums has limited length and is circular, there must be a cycle. 
            }
            if(p1==i && length>1) return true; // found a cycle with length greater than 1 starting from i
        }

        return false;
    }
};

No comments:

Post a Comment