Leetcode-141. Linked List Cycle

来源:互联网 发布:冢原卜传 知乎 编辑:程序博客网 时间:2024/05/17 02:06

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

博客链接:mcf171的博客

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

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

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

这个题简单一点就是用一个Set保存访问过的点。Your runtime beats 3.79% of java submissions.

public class Solution {    public boolean hasCycle(ListNode head) { Set<ListNode> set = new HashSet<ListNode>();boolean flag = false;while(head != null){if(set.contains(head)) {flag = true;break;}else{set.add(head); head = head.next;flag = false;}}return flag;    }}
不使用额外空间的话,论坛一个人太机智了。见代码Your runtime beats 9.64% of java submissions.

public class Solution {    public boolean hasCycle(ListNode head) {        boolean flag = false;ListNode search = head;while(search != null){if(search.next == head) return true;ListNode temp = search.next;search.next = head;search = temp;}return flag;    }}





0 0
原创粉丝点击