环形链表,力扣141

给你一个链表的头节点 head ,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。
如果链表中存在环 ,则返回 true 。 否则,返回 false 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路一:
由于题目需要pos来表示链表情况,我的第一想法是通过ArrayList存储每个节点。然后再对比判断下一个节点是否在ArrayList中存在。

public class Solution {
    public boolean hasCycle(ListNode head) {
        int pos = -1;
		List<ListNode> list = new ArrayList<>();
		if(head==null||head.next==null) {
			return false;
		}
		while(head.next!=null) {
			if((pos = list.indexOf(head))>=0) {
				return true;
			}
			list.add(head);
			head = head.next;
		}
		return false;
    }
}

在这里插入图片描述

很明显,这样做的时空复杂度都很高。因为list.indexOf底层是循环遍历。list的长度又等于整个链表的长度。结果俺去看官方题解,发现第一种HashSet,思路其实和我一样,时空复杂度低很多,但是pos呢?全篇看不到pos这个参数名。灵机一动,HashMap不就好了。


**这是官方题解方式一,采用HashSet。**
public class Solution {
    public boolean hasCycle(ListNode head) {
        Set<ListNode> seen = new HashSet<ListNode>();
        while (head != null) {
            if (!seen.add(head)) {
                return true;
            }
            head = head.next;
        }
        return false;
    }
}


**咱们稍微改进一下,为了取到那个pos值。**
public class Solution {
    public boolean hasCycle(ListNode head) {
        int pos=-1;
		int i=0;
		Map<ListNode,Integer> map = new HashMap<>();
        while (head != null) {
        	//如果Map中存在该节点,那么记录pos位置,返回true
            if (map.get(head)!=null) {
            	pos=map.get(head);
                return true;
            }
            map.put(head, i++);
            head = head.next;
        }
        return false;
    }
}

在这里插入图片描述


至于采用**快慢指针**的方式,俺觉得得不到pos值。但姑且还是记录一下。
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head==null||head.next==null) {
			return false;
		}
		ListNode node = head.next;
        while (head!=node) {
            if(node==null||node.next==null) {
            	return false;
            }
            head = head.next;
            node = node.next.next;
        }
        return true;
    }
}

在这里插入图片描述

记录俺的成长过程。如果有更好的方法也可以让我学习一哈。阿里嘎多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值