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?

题解

这个问题本来有很多种解法,比如拓扑排序,DFS, BFS等,但是由于O(1)空间复杂度的限制我们只能在原数组上进行原地操作。因此我们仍然可以采用DFS,需要在原数组上把已经访问过的无法成环的位置标记为0。同时需要进行一些预处理,把指向自己的坏环标记为0。

代码

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

class Solution {
private:
public:
    bool circularArrayLoop(vector<int>& nums) {
        for(int i = 0; i < nums.size(); i++){
            int next = nextNode(nums, i);
            if(next == i){
                nums[i] = 0;
            }
        }
        for(int i = 0; i < nums.size(); i++){
            if(nums[i] == 0){
                continue;
            }
            int next = nextNode(nums, i);
            bool direction = nums[i] > 0;
            while(true){
                if(nums[next] == 0){
                    break;
                }
                if(next == i){
                    return true;
                }
                if((nums[next] > 0) != direction){
                    break;
                }
                next = nextNode(nums, next);
            }
            nums[i] = 0;
        }
        return false;
    }

    int nextNode(vector<int> &nums, int i){
        int next = i + nums[i];
        if(next < 0){
            next  = nums.size() + next;
        }
        next = next % nums.size();
        return next;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值