已解决
算法训练 第三周
来自网友在路上 152852提问 提问时间:2023-09-20 03:56:24阅读次数: 52
最佳答案 问答题库528位专家为你答疑解惑
二、环形链表
本题给了我们一个链表的头节点,需要我们判断这个链表之中是否存在环状结构,如果存在返回true,如果不存在则返回false。
1.hash表
我们可以从头遍历整个链表,并将遍历到的节点放入一个hashset中,当我们遍历到的节点与hashset中的节点出现重复时就说明链表存在环,如果我们遍历完了整个链表那就说明不存在环,具体代码如下:
/*** 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 || head.next == null) {return false;}ListNode node = head;HashSet<ListNode> set = new HashSet<>();while(node != null) {if(set.contains(node)) {return true;}set.add(node);node = node.next;}return false;}
}
复杂度分析
- 时间复杂度:O(n)。
- 空间复杂度:O(n)。
2.双指针
我们可以定义两个指针来遍历这个链表,慢指针每次走一个节点,快指针每次走两个节点,如果在遍历的过程中快指针与慢指针相遇则说明有环,否则就没有环,具体代码如下:
/*** 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 || head.next == null) {return false;}ListNode f = head;ListNode s = head;while(f != null && f.next != null) {f = f.next.next;s = s.next;if(f == s) {return true;}}return false;}
}
复杂度分析
- 时间复杂度:O(n)。
- 空间复杂度:O(1)。
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"算法训练 第三周":http://eshow365.cn/6-9759-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: Spring 依赖注入和循环依赖
- 下一篇: B树的定义和特点