您的位置:首页 > 运维架构

leetcode 457. Circular Array Loop 数组中寻找环的存在+双指针+循环判断

2017-12-11 19:02 441 查看
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?

题意很简单,就是一个循环的判断,这道题可以使用双指针来判断,要注意的是双指针的移动要注意保持方向一致

所以在while的地方我们要求当前的和fast和fast的方向是一致的,这样才能全部AC

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>

using namespace std;

class Solution
{
public:
bool circularArrayLoop(vector<int>& a)
{
for (int i = 0; i < a.size(); i++)
{
if (a[i] == 0)
continue;
int slow = i, fast = getNextIndex(i, a);
while (a[i] * a[fast] > 0 && a[i] * a[getNextIndex(fast, a)] > 0)
{
if (slow == fast)
{
if (slow == getNextIndex(slow, a))
break;
else
return true;
}
else
{
slow = getNextIndex(slow, a);
fast = getNextIndex(getNextIndex(fast, a), a);
}
}
}
return false;
}

int getNextIndex(int i, vector<int>& a)
{
int size = a.size();
if (i + a[i] > 0)
return (i + a[i]) % size;
else
return ((i + a[i]) % size + size);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐