457. Circular Array Loop
Posted yaoyudadudu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 complexity?
解题思路:
首先我们要明确怎样算是一个环:
1. 起始坐标和结束坐标为同一坐标
2. 环中要有多于一个的元素
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; } };
以上是关于457. Circular Array Loop的主要内容,如果未能解决你的问题,请参考以下文章
[Algorithm] Search element in a circular sorted array
LC 918. Maximum Sum Circular Subarray