码迷,mamicode.com
首页 > 其他好文 > 详细

141. Linked List Cycle

时间:2019-02-05 22:17:21      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:tco   ini   null   run   nbsp   map   0.00   https   ssi   

源地址:https://leetcode.com/problems/linked-list-cycle/

判断链表是否有环路

 

首先最开始想到的办法是存储访问过的节点,之后看当前节点的next是否指向已经遍历过的节点,这样的时间复杂度是O(n),空间复杂度也是O(n)。使用ArrayList存储会非常慢,使用hashmap存储大概运行时间6 ms, faster than 12.13% of Java online submissions for Linked List Cycle. 

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null){
            return false;
        }
        HashMap<ListNode, Integer> map = new HashMap<>();
        int i = 0;
        while(head!= null){
            map.put(head, i++);
            head = head.next;
            if(map.containsKey(head)){
                return true;
            }
        }
        return false;
    }
}

 

为了是空间复杂度降至O(1), 使用快慢指针的方法。如果存在环路, 那么快慢指针一定会在某一点相遇,就好像在操场上跑圈一样,快的人一定会赶上慢的人,

这样运行Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle.

/**
 * 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;
        while(fast != null && fast.next!= null){
            fast = fast.next.next;
            head = head.next;
            if(head == fast){
                return true;
            }
        }
        return false;
    }
}

 

141. Linked List Cycle

标签:tco   ini   null   run   nbsp   map   0.00   https   ssi   

原文地址:https://www.cnblogs.com/clairexxx/p/10353173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!