原题链接在这里: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. Cpp_Primer_4th_Edition-source-code

    Cpp_Primer_4th_Edition-source-code 根据书上的去找,官网已经找不到了,毕竟第6版都已经出来了.不过有的朋友用的还是第4版,我的纸质书是第5版,pdf是第4版,都有在看 ...

  2. C语言return返回值深入理解

    C语言使用return关键字返回函数值,可以很好对函数做封装,此处的疑问是:函数内部创建的变量都是局部变量,即私有的,作用域就在函数之内,为什么却可以把值传给调用函数? 解释这个问题还需要从C语言调用 ...

  3. 【leetcode】590. N-ary Tree Postorder Traversal

    Recurisve: /* // Definition for a Node. class Node { public: int val; vector<Node*> children; ...

  4. HTML5+规范:Geolocation(管理设备位置信息) 定位

    Geolocation模块管理设备位置信息,用于获取地理位置信息,如经度.纬度等.通过plus.geolocation可获取设备位置管理对象.虽然W3C已经提供标准API获取位置信息,但在某些平台存在 ...

  5. -透明度中百分比与十六进制的对应关系 MD

    目录 目录 透明度中百分比与十六进制的对应关系 计算代码 对应关系表 Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao ...

  6. Fiddler的使用总结

    关于Fiddler的使用过程中的总结: 1. 配置手机抓包的过程,以后再补充 2.使用Fiddler发送请求 1) 第一步 抓取接口,获取请求方式,以及请求参数  2) 第二步 请求接口 点击Exec ...

  7. vim安装 YCM 过程记录

    YCM(YouComplateMe) 属于Vim中大神级的插件,提供了类似于巨硬爸爸的VS中的代码补全,但是其安装方式也是比较复杂,因此特意写下一篇记录,记录下我自己如何安装这一插件的过程: 检查自己 ...

  8. NEST refresh flush forcemerge

    public void Refresh() { client.Refresh("employee"); } public void Flush() { client.Flush(& ...

  9. swagger2 404

    swagger2 404 正确配置swagger后(配置),出现404问题. 如图: 分析原因 我是在配置完成swagger后正常使用过一段时间的,然后检查了相关配置项的代码,没有被改动过.可以确定s ...

  10. HTML学习摘要1

    在http://www.w3school.com.cn/ 学习前端知识,利用暑假,自主学习以拓展知识面 DAY 1 HTML 不是一种编程语言,而是一种标记语言 (markup language) 标 ...