問題描述:數組
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; } };