LeetCode实战:环形链表



题目英文

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list.

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

题目中文

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果pos是 -1,则在该链表中没有环。

示例 1

输入:head = [3,2,0,-4], pos = 1 输出:true 解释:链表中有一个环,其尾部连接到第二个节点。

示例 2

输入:head = [1,2], pos = 0 输出:true 解释:链表中有一个环,其尾部连接到第一个节点。

示例 3

输入:head = [1], pos = -1 输出:false 解释:链表中没有环。

进阶

你能用 O(1)(即,常量)内存解决此问题吗?

算法实现

/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { * val = x; * next = null; * } * } */ // 通过检查一个结点此前是否被访问过来判断链表是否为环形链表。 public class Solution { public bool HasCycle(ListNode head) { HashSet hashSet = new HashSet(); hashSet.Add(head); while (head != null) { head = head.next; if (head == null) return false; if (hashSet.Contains(head)) return true; hashSet.Add(head); } return false; } }

实验结果

状态:通过17 / 17 个通过测试用例执行用时:144 ms

提交结果

相关图文

LeetCode实战:删除链表的倒数第N个节点LeetCode实战:合并两个有序链表LeetCode实战:两两交换链表中的节点LeetCode实战:旋转链表LeetCode实战:相同的树LeetCode实战:对称二叉树LeetCode实战:二叉树的最大深度LeetCode实战:搜索二维矩阵LeetCode实战:将有序数组转换为二叉搜索树资料分享:数学建模资料分享 -- 图论部分资料分享:数学建模资料分享 -- 神经网络部分如何利用 C# 实现 K 最邻近算法?如何利用 C# 实现 K-D Tree 结构?如何利用 C# + KDTree 实现 K 最邻近算法?如何利用 C# 对神经网络模型进行抽象?如何利用 C# 实现神经网络的感知器模型?如何利用 C# 实现 Delta 学习规则?如何利用 C# 实现 误差反向传播 学习规则?如何利用 C# 爬取带 Token 验证的网站数据?如何利用 C# 向 Access 数据库插入大量数据?如何利用 C# + Python 破解猫眼电影的反爬虫机制?

经过8年多的发展,LSGO软件技术团队在「地理信息系统」、「数据统计分析」、「计算机视觉」等领域积累了丰富的研发经验,也建立了人才培养的完备体系,由于自己准备在「量化交易」领域精进技能,如果大家对这个领域感兴趣可以与我联系,加入我们的量化学习群一起学习探讨。

在这个领域我已做了以下积累:

策略部分:

数字货币 One 的投资价值分析数字资产量化中的跨市场套利策略数字资产量化中的同市场套利策略数字资产量化中的网格交易法我们能否效仿李笑来的投资策略?赚钱是刚需,如何正确的交易股票?

数据部分:

如何利用 C# 爬取 One 的交易数据?如何利用 C# 爬取 One 持有者返利数据?如何利用 C# 爬取BigOne交易所的公告?如何利用 C# 爬取Gate.io交易所的公告?如何利用 C# 爬取「财报说」中的股票数据?

自动化交易部分:

封装BigOne API:身份验证封装BigOne API:获取账户资产封装BigOne API:订单系统封装BigOne API:网格交易法封装BigOne API:代码的重构进一步完善自动化交易系统 01进一步完善自动化交易系统 02进一步完善自动化交易系统 03进一步完善自动化交易系统 04如何开发「股票数据分析软件」(上)如何开发「股票数据分析软件」(中)如何开发「股票数据分析软件」(下)进一步完善「股票数据分析软件」 - 01

后台回复「搜搜搜」,随机获取电子资源!

欢迎关注,请扫描二维码: