zoukankan      html  css  js  c++  java
  • 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?

    解题思路:

    首先我们要明确怎样算是一个环:

      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;
        }
    };
  • 相关阅读:
    开课博客
    高级UI组件(二)
    《梦断代码》读后感(三)
    高级UI组件
    今日总结
    今日总结
    android中关于时间的控件
    单选按钮和复选框
    Android开发中按钮的语法
    布局管理器的嵌套
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9393758.html
Copyright © 2011-2022 走看看