LeetCode #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?

以当前元素的数值作为前进或者后退的步数,遍历到下一个元素,而且要求在一个环中必须全部是前进或者全部是后退,按照以上的遍历规则,求问数组中是否存在环,要求O(n)的时间复杂度和O(1)的空间复杂度。

class Solution {
public:
    bool circularArrayLoop(vector<int>& nums) {
        int n=nums.size();
        if(n<=1) return false;
        for(int i=0;i<n;i++)
        {
            int slow=i;
            int fast=i;
            while(nums[slow]*nums[i]>0&&nums[fast]*nums[i]>0&&nums[next(nums,slow)]*nums[i]>0)
            {
                //在该循环中不可以对已访问的元素进行标记,否则改变元素值之后
                //接下来的移动就会错误,所以这个循环只判断从i开始是否有环
                slow=next(nums,slow);
                fast=next(nums,fast);
                fast=next(nums,fast);
                if(slow==fast) 
                {
                    if(slow==next(nums,slow)) break;//由于环最少需要2个元素,自身循环不是环,例如[1,2]
                    else return true;
                }
            }
            //从i开始无环,对访问过的元素标记为0,这样下一次访问这个元素一定会跳过
            //因为从i开始访问的元素都不可能形成环
            slow=i;
            while(nums[slow]*nums[i]>0)//移动方向必须同向
            {
                nums[slow]=0;
                slow=next(nums,slow);
            }
        }
        return false;
    }
    
    int next(vector<int> nums, int i)
    {
        int n=nums.size();
        if((nums[i]+i)<0) return nums[i]+i+n;
        else return (nums[i]+i)%n;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值