难度 中等
题目 Leetcode:
Circular Array Loop
You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i:
If nums[i] is positive, move nums[i] steps forward, and
If nums[i] is negative, move nums[i] steps backward.
Since the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.
A cycle in the array consists of a sequence of indices seq of length k where:
Following the movement rules above results in the repeating index sequence seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...
Every nums[seq[j]] is either all positive or all negative.
k > 1
Return true if there is a cycle in nums, or false otherwise.
题目解析
感觉中等比昨天的困难还麻烦,长话短说吧。
这样一题的思路就是拓扑排序,具体的思路看注释吧
解析完毕,以下是参考代码
1 class Solution { 2 public: 3 queue<int> q; 4 bool circularArrayLoop(vector<int>& nums) { 5 int n = nums.size(); 6 vector<vector<int>> g(n);//存储情况 7 vector<int> x(n);//入度数组 8 for (int i = 0; i < n; i++) //先处理回环和异号的情况 9 { 10 int temp = ((i + nums[i]) % n + n) % n; 11 if (temp == i || nums[i] * nums[temp] < 0) continue;//如果闭环或反向就不标记 12 g[i].push_back(temp); 13 x[temp]++; 14 } 15 for (int i = 0; i < n; i++)//将所有入度为0的入队 16 if (!x[i]) q.push(i); 17 int cnt = 0; 18 while (!q.empty()) 19 { 20 int temp = q.front();//遍历所有从temp起始的有向边,并使其指向的终点入度-1 21 q.pop(); 22 for (auto & node : g[temp]) 23 if (!(--x[node])) //入度为0才入队 24 q.push(node); 25 cnt++; 26 } 27 return (cnt == n)?0:1; 28 } 29 };
原文:https://www.cnblogs.com/lovetianyi/p/15113781.html