原题链接在这里: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. Django框架之DRF APIView Serializer

    一.APIView 我们在使用DjangoRestfulFramework的时候会将每个视图类继承APIView,取代原生Django的View类 APIView的流程分析: rest_framewo ...

  2. ubuntu 安装harbor仓库

    一.介绍 Harbor,是一个英文单词,意思是港湾,港湾是干什么的呢,就是停放货物的,而货物呢,是装在集装箱中的,说到集装箱,就不得不提到Docker容器,因为docker容器的技术正是借鉴了集装箱的 ...

  3. Golang ---testing包

    golang自带了testing测试包,使用该包可以进行自动化的单元测试,输出结果验证,并且可以测试性能. 建议安装gotests插件自动生成测试代码: go get -u -v github.com ...

  4. 使用StringBuilder构建字符串

    使用StringBuilder构建字符串确实可以提高效率,比“+”要高效不少.但使用时也有一些坑: 首先,我们指定一个StringBuilder,并设置其长度. StringBuilder build ...

  5. 2019 拼多多java面试笔试题 (含面试题解析)

    本人3年开发经验.18年年底开始跑路找工作,在互联网寒冬下成功拿到阿里巴巴.今日头条.拼多多等公司offer,岗位是Java后端开发,最终选择去了拼多多. 面试了很多家公司,感觉大部分公司考察的点都差 ...

  6. testNG helloWorld

    1. 新建maven工程.File -> New -> Project -> Maven,不选Create from archetype,直接点击“Next”.GroupId和Art ...

  7. iOS学习——iOS项目增加新的字体

    基本思路 在项目开发过程中,iOS系统自带的字体库可能不适应需求,需要导入其他的字体库.下面是iOS项目增加新的字体的基本思路,基本上分为三步: 将字体库添加到项目中 在info.plist中添加所需 ...

  8. Unity Physicals Rigidbody with multiple colliders

    Rigidbody with multiple colliders adding colliders changes the center of mass and rotation behaviour ...

  9. linux技能点 一

    vmware  workstation:安装时永久性密钥   5A02H-AU243-TZJ49-GTC7K-3C61N  linux技能点:系统管理,网络管理,文件操作,用户管理,文件权限,软件管理 ...

  10. 【OGG】 RAC环境下管理OGG的高可用 (五)

    [OGG] RAC环境下管理OGG的高可用 (五) 一.1  BLOG文档结构图 一.2  前言部分 一.2.1  导读 各位技术爱好者,看完本文后,你可以掌握如下的技能,也可以学到一些其它你所不知道 ...