Linked List Cycle:判断链表是否有环
来源:互联网 发布:windows怎么修改快捷键 编辑:程序博客网 时间:2024/05/31 04:03
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解释:题目言简意赅,判断是否有环。
有三种情况:无环、中途有环、首尾相接
思路一: 遍历全链,每个已遍历节点存入hash表中,发生冲突即为有环。
时间复杂度:O(n) 遍历全表
空间复杂风度:O(n) hash表存储全链
public boolean hasCycle(ListNode head) { Set<ListNode> nodesSeen = new HashSet<>(); while (head != null) { if (nodesSeen.contains(head)) { return true; } else { nodesSeen.add(head); } head = head.next; } return false; }
思路二:两个指针:fast每次移动两格,slow每次移动一格。若存在环,则在O(K)时间内fast可追上slow,K为环的长度。再加上未进入环时所耗时O(N),时间复杂度O(N+K),即O(N)
空间复杂度O(1)
/** * 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 fast = head.next; ListNode slow = head; while(fast!=slow){ if(fast.next==null||fast.next.next==null) return false; fast = fast.next.next; slow = slow.next; } return true; }}
阅读全文
0 0
- 判断链表是否有环 Linked List Cycle, Linked List Cycle II
- 判断链表是否有环 Linked List Cycle
- Linked List Cycle --判断链表是否有环
- leetcode--Linked List Cycle--判断链表是否有环
- Linked List Cycle 判断链表是否有环
- Linked List Cycle:判断链表是否有环
- Linked List Cycle 判断链表是否有环,如果有环,找到环的入口
- LeetCode | Linked List Cycle(判断链表是否有环)
- LeetCode OJ 之 Linked List Cycle (判断链表是否有环)
- LeetCode OJ 之 Linked List Cycle II(判断链表是否有环 - 二)
- 【leetcode】Linked List Cycle II,判断链表是否有环
- [LeetCode-141] Linked List Cycle(判断链表是否有环)
- 链表-Linked List Cycle II(判断一个链表是否有环)
- 【Leetcode】141. Linked List Cycle-判断链表是否有环
- leetcode解题之141# Linked List Cycle Java版 (判断链表是否有环)
- Linked List Cycle 链表是否有环
- 141. Linked List Cycle 判断单链表中是否有环
- leetcode_141. Linked List Cycle 判断链表中是否有环
- 统计不同时间段在线人数,给定若干(进入,离开)时间对
- java迭代器
- 左右括号全排列
- Codeforces Round #436 (Div. 2) A.Fair Game B.Polycarp and Letters C. Bus D.Make a Permutation!
- [kuangbin带你飞]专题十七 AC自动机 D Detect the Virus
- Linked List Cycle:判断链表是否有环
- 取消ssh,scp 询问
- Java 重写(Override)与重载(Overload)
- 渐变圆环进度条实现
- ARKit开发-简介及Demo展示
- Docker CE for Ubuntu安装笔记
- Delete Node In A LinkedList
- JZOJ 5385. 【NOIP2017提高A组模拟9.23】Carry
- maven项目配置