作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址: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?

题目大意

首先,要理解题目中的「环形数组」是什么。「环形数组」就是在逻辑上首尾相接的数组即最后一个元素和第一个元素在逻辑上是相邻的(在物理存储上仍然是个普通的数组)。

那么环形数组中存在循环是什么意思呢?这就是说,在环形数组中,每个位置存储的元素表示当前位置应该向前/向后移动的步数。如果在环形数组中绕了一圈又回到了原地,那么说明数组中存在循环。

举个例子,在环形数组 [2, -1, 1, 2, 2] 中,存在循环:

同时,题目约定了循环的条件:

  • 所有 nums[seq[j]] 应当不是 全正 就是 全负,即只能沿着一个方向走。
  • k > 1,即要求环的大小 > 1。

题目的示例 2 和 3 说明了上述循环的条件。

示例 2 ,nums = [-1,2],不算循环的原因是,循环中只有一个元素:

示例 3,nums = [-2,1,-1,-2,-2],不算循环的原因是,循环中同时存在正、负数。

另外,需要提醒大家的是:循环的起点并不一定是位置 0.

解题思路

快慢指针

相信大家都做过「判断链表中是否有环」的题目,这两题的思路是一致的,常见的思路就是快慢指针,在链表问题中,快指针每次走 2 步,慢指针每次走 1 步。当快慢指针相遇的时候,说明存在环。

在本题中,题目规定了数组中每个位置存储的元素就是每次需要移动的步数。所以快指针、慢指针每次走的步数等于 nums[fast]、nums[slow];在每一次的移动中,快指针需要走 2 次,而慢指针需要走 1 次。当快慢指针相遇的时候,说明有环。

起始时,让快指针先比慢指针多走一步,当两者在满足题目的两个限制条件的情况下,快满指针能够相遇,则说明有环。

这个题难点在于题目的两个限制条件:

  1. 在每次循环的过程中,必须保证所经历过的所有数字都是同号的。

    1. 那么,在快指针经历过的每个位置都要判断一下和出发点的数字是不是相同的符号。
  2. 当快慢指针相遇的时候,还要判断环的大小不是 1。
    1. 所以,找到相遇点的位置后,如果再走 1 步,判断是不是自己。

下面的动图展示了在环形数组 [2, -1, 1, 2, 2] 中,如何利用快慢指针寻找判断环形数组中是否存在环。

代码

在下面的代码中,我定义了一个 nextpos(index)的函数,用于判断每次移动后应该走到哪个位置。

Python代码如下:

class Solution(object):
def circularArrayLoop(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
N, self.nums = len(nums), nums
for i in range(N):
slow = i
fast = self.nextpos(slow)
while nums[fast] * nums[i] > 0 and nums[self.nextpos(fast)] * nums[i] > 0:
if fast == slow:
if slow == self.nextpos(slow):
break
return True
slow = self.nextpos(slow)
fast = self.nextpos(self.nextpos(fast))
return False def nextpos(self, index):
N = len(self.nums)
return (index + self.nums[index] + N) % N

日期

2019 年 2 月 27 日 —— 二月就要完了
2021 年 8 月 7 日 —— 开始更新算法每日一题

【LeetCode】457. Circular Array Loop 环形数组是否存在循环 解题报告(Python)的更多相关文章

  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] Circular Array Loop 环形数组循环

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

  3. LeetCode 457. Circular Array Loop

    原题链接在这里:https://leetcode.com/problems/circular-array-loop/ 题目: You are given a circular array nums o ...

  4. LeetCode 1013 Partition Array Into Three Parts With Equal Sum 解题报告

    题目要求 Given an array A of integers, return true if and only if we can partition the array into three  ...

  5. 【LeetCode】109. Convert Sorted List to Binary Search Tree 解题报告(Python)

    [LeetCode]109. Convert Sorted List to Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id ...

  6. 【LeetCode】378. Kth Smallest Element in a Sorted Matrix 解题报告(Python)

    [LeetCode]378. Kth Smallest Element in a Sorted Matrix 解题报告(Python) 标签: LeetCode 题目地址:https://leetco ...

  7. 【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)

    [LeetCode]863. All Nodes Distance K in Binary Tree 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http ...

  8. 【LeetCode】331. Verify Preorder Serialization of a Binary Tree 解题报告(Python)

    [LeetCode]331. Verify Preorder Serialization of a Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https:/ ...

  9. 【LeetCode】452. Minimum Number of Arrows to Burst Balloons 解题报告(Python)

    [LeetCode]452. Minimum Number of Arrows to Burst Balloons 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https ...

随机推荐

  1. Windows下的Python多版本管理?

    虽然接触了好几年python,但一些细节没有注意.最近看网课,看到这个Windows系统下Python多版本管理的问题,记录下备忘. 假设现在windows环境中有python2,python3和an ...

  2. PHP socket Workerman实用的php框架

    PHP socket Workerman是一款开源高性能异步PHP socket即时通讯框架. 非常好用的一款框架,可以支持在线聊天,长连接等 用法 官方 https://www.workerman. ...

  3. orcale => 含义

    => 是 Oracle 中调用 存储过程的时候, 指定 参数名进行调用.ps(说实话,就是Oracle再执行存储过程中,类似于在word中进行替换一样的感觉,比如说你默认的情况下是你定义了默认参 ...

  4. Scrapy爬虫框架的安装和使用

    Scrapy是一个十分强大的爬虫框架,依赖的库比较多,至少需要依赖的库有Twisted 14.0.lxml 3.4和pyOpenSSL 0.14.在不同的平台环境下,它所依赖的库也各不相同,所以在安装 ...

  5. (转载) IBM DB2数据库odbc配置步骤详解

    [IT168 技术] 首先安装IBM DB2 odbc driver 1):可以单独下载DB2 Run-Time Client,大约(86.6m),安装后则odbc驱动程序安装成功.下载地址:ftp: ...

  6. IO流的字节输入输出流(InputStream,OutputStream)

    字节输出流与文件字节输出流 文件存储原理和记事本打开文件原理 OutputStream及FileOutputStream import java.io.FileOutputStream; import ...

  7. 作为Java技术面试官,我如何深挖候选人的技能

    作为Java资深技术面试官,首先我感觉有必要讲解"面试官深挖问题"的动机,在了解动机的前提下,大家才能更好地准备面试.面试官为什么要在一个点上深挖?两大目的.   1 首先是通过深 ...

  8. set、multiset深度探索

    set/multiset的底层是rb_tree,因此它有自动排序特性.set中的元素不允许重复必须独一无二,key与value值相同,multiset中的元素允许重复. set的模板参数key即为关键 ...

  9. JPA和事务管理

    JPA和事务管理 很重要的一点是JPA本身并不提供任何类型的声明式事务管理.如果在依赖注入容器之外使用JPA,事务处理必须由开发人员编程实现. 123456789101112UserTransacti ...

  10. 【Linux】【Services】【SaaS】Docker+kubernetes(10. 利用反向代理实现服务高可用)

    1. 简介 1.1. 由于K8S并没有自己的集群,所以需要借助其他软件来实现,公司的生产环境使用的是Nginx,想要支持TCP转发要额外安装模块,测试环境中我就使用HAPROXY了 1.2. 由于是做 ...