原题链接在这里:https://leetcode.com/problems/circular-array-loop/

题目:

You are given a circular array nums of positive and negative integers. If a number k at an index is positive, then move forward k steps. Conversely, if it's negative (-k), move backward k steps. Since the array is circular, you may assume that the last element's next element is the first element, and the first element's previous element is the last element.

Determine if there is a loop (or a cycle) in nums. A cycle must start and end at the same index and the cycle's length > 1. Furthermore, movements in a cycle must all follow a single direction. In other words, a cycle must not consist of both forward and backward movements.

Example 1:

Input: [2,-1,1,2,2]
Output: true
Explanation: There is a cycle, from index 0 -> 2 -> 3 -> 0. The cycle's length is 3.

Example 2:

Input: [-1,2]
Output: false
Explanation: The movement from index 1 -> 1 -> 1 ... is not a cycle, because the cycle's length is 1. By definition the cycle's length must be greater than 1.

Example 3:

Input: [-2,1,-1,-2,-2]
Output: false
Explanation: The movement from index 1 -> 2 -> 1 -> ... is not a cycle, because movement from index 1 -> 2 is a forward movement, but movement from index 2 -> 1 is a backward movement. All movements in a cycle must follow a single direction.

Note:

  1. -1000 ≤ nums[i] ≤ 1000
  2. nums[i] ≠ 0
  3. 1 ≤ nums.length ≤ 5000

Follow up:

Could you solve it in O(n) time complexity and O(1) extra space complexity?

题解:

Use walker and runner pointers to check if there is a loop.

Every time, pointer move as i + nums[i]. If it is positive, return (i + nums[i])/nums.length. If it is negative, return (i+nums[i])/nums.length + nums.length.

In order to maintain the same direction, make sure each shifted index are all positive or all negative.

When walker and runner meets, then there is a loop.

But in case to avoid single element in the loop, check if next move is still here.

Last, if there is no loop for current routine, then mark all nums on this routine as 0, then there would not be duplicate calcuation on these numbers.

Time Complexity: O(n). n = nums.length.

Space: O(1).

AC Java:

 class Solution {
public boolean circularArrayLoop(int[] nums) {
if(nums == null || nums.length < 2){
return false;
} for(int i = 0; i<nums.length; i++){
if(nums[i] == 0){
continue;
} int walker = i;
int runner = i;
while(nums[i]*nums[shift(runner, nums)]>0 && nums[i]*nums[shift(shift(runner, nums), nums)]>0){
walker = shift(walker, nums);
runner = shift(shift(runner, nums), nums);
// If there is a loop, walker and runner will meet
if(walker == runner){
// If there is only one element in loop, break while
if(walker == shift(walker, nums)){
break;
} return true;
}
} // When there is no loop with current routine,
// Mark value as 0, then there would not be duplicate calculation
int ind = i;
int val = nums[ind];
while(val*nums[ind]>0){
int nextInd = shift(ind, nums);
nums[ind] = 0;
ind = nextInd;
}
} return false;
} private int shift(int i, int [] nums){
int n = nums.length;
return i + nums[i] >= 0 ? (i + nums[i]) % n : (i + nums[i]) % n + n;
}
}

类似Linked List Cycle.

LeetCode 457. Circular Array Loop的更多相关文章

  1. [LeetCode] 457. Circular Array Loop 环形数组循环

    You are given a circular array nums of positive and negative integers. If a number k at an index is ...

  2. 【LeetCode】457. Circular Array Loop 环形数组是否存在循环 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题思路 快慢指针 代码 日期 题目地址:https://le ...

  3. [LeetCode] Circular Array Loop 环形数组循环

    You are given an array of positive and negative integers. If a number n at an index is positive, the ...

  4. Leetcode: Circular Array Loop

    You are given an array of positive and negative integers. If a number n at an index is positive, the ...

  5. [Swift]LeetCode457. 环形数组循环 | Circular Array Loop

    You are given an array of positive and negative integers. If a number n at an index is positive, the ...

  6. LeetCode:Convert Sorted Array to Binary Search Tree,Convert Sorted List to Binary Search Tree

    LeetCode:Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in asce ...

  7. [LeetCode] 805. Split Array With Same Average 用相同均值拆分数组

    In a given integer array A, we must move every element of A to either list B or list C. (B and C ini ...

  8. [LeetCode] Shuffle an Array 数组洗牌

    Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. int[] n ...

  9. [LeetCode] Sort Transformed Array 变换数组排序

    Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f( ...

随机推荐

  1. 2019-7-16 import / from...import... 模块的调用

    模块调用的总结:如果你是pycharm打开文件,会自动帮你把文件根目录加到system.path中,你要调用模块直接以根目录为基准开始找.1.假如你要调用和文件根目录为同级的文件,你直接import ...

  2. vim 自定义设置

    修改系统配置(面对所有用户): root@bogon:~# cd /etc/vim/ root@bogon:/etc/vim# ls vimrc vimrc.tiny root@bogon:/etc/ ...

  3. 牛客CSP-S提高组赛前集训营2 T2沙漠点列

    原题链接 算法不难,比赛的时候就和cyc大佬一起yy了正解,不过因为交的时候比较急(要回寝室惹),我有两数组开错大小直接爆到50,cyc大佬则只把文件输入关了一半,直接爆零(╯ ̄Д ̄)╯┻━┻ 要尽量 ...

  4. lsb_release -a linux查看版本未找到命令

    解决方案 yum install -y redhat-lsb 安装完后

  5. SQL Server——死锁查看

    一.通过语句查看 --查询哪些死锁SELECT request_session_id spid, OBJECT_NAME( resource_associated_entity_id ) tableN ...

  6. Tomcat组件梳理--Server

    Tomcat组件梳理--Server 1.Server组件的定义和功能概述 定义: Server组件用于描述一个启动的Tomcat实例,一个Tocmat被启动,在操作系统中占用一个进程号,提供web服 ...

  7. sql分页优化

    索引优化 注意查询的数据占总数据达到一定量的时候可能导致索引失效.可以用limit或者指定列缩小数据区域可以解决. 以时间orderby排序的limit分页优化 前提用order by分页 limit ...

  8. 在element-ui label中设置空格

    处理之前的效果 处理之后 处理方法: <el-form-item label="类型" required> <label slot="label&quo ...

  9. Java 之 ServletContext 对象

    ServletContext 对象 一.概念 ServletContext对象:代表整个 web 应用,可以和程序的容器(服务器)来通信. 二.获取 1.通过request 获取 方法: reques ...

  10. property Alternative forms propretie

    property Alternative forms propretie English English Wikipedia has articles on: Property (disambigua ...