LeetCode笔记:141. Linked List Cycle
来源:互联网 发布:js xml格式化显示代码 编辑:程序博客网 时间:2024/05/22 06:07
问题:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
大意:
给出一个链表,判断它有没有回环。
进阶:
你能不能不用额外的空间来解决?
思路:
这道题我利用Java中Set集合的特性,即集合中不允许出现相同的对象。
我们遍历链表,边遍历边把每个节点放入一个Set集合中,并且每次都判断Set集合内对象的个数是否增加了,如果没增加,说明有相同的对象加入,也就是有回环了。
我看别人的解决办法,很多都是判断相邻的节点间有没有回环,其实不太理解,是不是回环只有相邻的这种情况呢,那如果存在大回环不是就判断不出来了么,还是觉得Set的方法比较保险。
代码(Java):
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public boolean hasCycle(ListNode head) { if (head == null) return false; HashSet list = new HashSet(); list.add(head); int num = 1; while (head.next != null) { list.add(head.next); num++; if (num > list.size()) return true; head = head.next; } return false; }}
合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_
0 0
- LeetCode笔记:141. Linked List Cycle
- 【LeetCode笔记】Linked List Cycle
- leetcode笔记:Linked List Cycle
- leetcode笔记--Linked List Cycle
- [LeetCode]141.Linked List Cycle
- LeetCode 141. Linked List Cycle
- [Leetcode] 141. Linked List Cycle
- LeetCode 141. Linked List Cycle
- [leetcode] 141.Linked List Cycle
- leetcode 141.Linked List Cycle
- [leetcode] 141. Linked List Cycle
- [LeetCode]141. Linked List Cycle
- 141. Linked List Cycle LeetCode
- [LeetCode]141. Linked List Cycle
- LeetCode 141. Linked List Cycle
- LeetCode *** 141. Linked List Cycle
- [LeetCode]141. Linked List Cycle
- LeetCode 141. Linked List Cycle
- 私有构造函数的作用
- 如何获取签名.jks中的SHA1
- C#中out和ref之间的区别
- html5 检测浏览器是否支持新特性
- leetCode练习(64)
- LeetCode笔记:141. Linked List Cycle
- Linux环境下Python2.7
- 常用正则表达式
- invoke方法学习
- iOS之UITextField 详解
- font config 问题实践 001 - 如何获取font config的配置文件
- php通过GD库实现验证码
- Win10离线安装.NET Framework 3.5的方法
- SSH框架总结