leetcode 457. Circular Array Loop 双指针 + 循环判断

来源:互联网 发布:达内java速成班 编辑:程序博客网 时间:2024/06/05 23:55

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?

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

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <cmath>using namespace std;class Solution {public:    bool circularArrayLoop(vector<int>& nums)     {        for (int i = 0; i < nums.size(); i++)        {            if (nums[i] == 0)                continue;            int j = i, k = getNextIndex(i, nums);            while (nums[i] * nums[k] > 0 && nums[i] * nums[getNextIndex(k,nums)] > 0)            {                if (j == k)                {                    if (j == getNextIndex(j, nums))                        break;                    else                        return true;                }                else                {                    j = getNextIndex(j, nums);                    k = getNextIndex(getNextIndex(k, nums), nums);                }            }        }        return false;    }    int getNextIndex(int i, vector<int>& nums)    {        int size = nums.size();        if (i + nums[i] > 0)            return (i + nums[i]) % size;        else            return ((i + nums[i]) % size + size);    }};
原创粉丝点击