码迷,mamicode.com
首页 > 其他好文 > 详细

457. Circular Array Loop

时间:2018-07-31 11:08:04      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:class   font   note   this   min   存在   strong   解题思路   int   

问题描述:

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

标签:class   font   note   this   min   存在   strong   解题思路   int   

原文地址:https://www.cnblogs.com/yaoyudadudu/p/9393758.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!