Leetcode-142. Linked List Cycle II

来源:互联网 发布:组织架构优化原则 编辑:程序博客网 时间:2024/06/16 19:31

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

这个题目没想到这么不用额外空间,用Set的话挺好解决的。Your runtime beats 2.27% of java submissions.

public class Solution {    public ListNode detectCycle(ListNode head) {        Set<ListNode> set = new HashSet<ListNode>();ListNode node = null;while(head != null){if(set.contains(head)) {node = head;break;}else{set.add(head); head = head.next;}}return node;    }}
这个写的好不使用额外空间solve




0 0
原创粉丝点击