LinkedList——No.141:Linked List Cycle

Problem:

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

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Explanation:

给定一个链表,判断是否有环。

My Thinking:

正向遍历链表,每遍历一个局结点就重新遍历检查该结点的下一个结点是否是之前的结点。

My Solution:

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode cur=head;
        ListNode check=head;
        while(cur!=null){
            while(check!=cur){
                if(cur.next==check){
                    return true;
                }else{
                    check=check.next;
                }
            }
            cur=cur.next;
            check=head;
        }
        return false;
    }
}

发现运行失败。

Optimum Thinking:

  1. 使用HashSet存放出现过的结点,使用contains方法判断结点是否已经出现过,时间复杂度为O(n)。
  2. 使用两个指针slow和fast,fast移动的速度是slow的两倍,如果出现环,fast一定会与slow相遇,时间复杂度为O(n)

Optimum Solution:

(1)

public class Solution {
    public boolean hasCycle(ListNode head) {
        Set<ListNode> nodeset=new HashSet<>();
        while(head!=null){
            if(nodeset.contains(head)){
                return true;
            }else{
                nodeset.add(head);
            }
            head=head.next;
        }
        return false; 
    }
}

(2)

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode fast=head;
        ListNode slow=head;
        while(fast!=null && fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
            if(slow==fast){
               return true;
            }
    }
        return false;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值