博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode82】Linked List Cycle
阅读量:4446 次
发布时间:2019-06-07

本文共 1380 字,大约阅读时间需要 4 分钟。

题目描述:

判断有序list是不是环

要求:

时间复杂度o(n)

原文描述:

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

Follow up:

Can you solve it without using extra space?

思路:

  • 设置两个指针,一个快指针,每次走两步,一个慢指针,每次走一步
  • 如果块指针==慢指针,那么包含环
  • 注意判断空值和长度为一的情况
    -

代码:

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

更多leetcode题目,请看我的leetcode专栏。链接如下:

我的微信二维码如下,欢迎交流讨论

这里写图片描述

欢迎关注《IT面试题汇总》微信订阅号。每天推送经典面试题和面试心得技巧,都是干货!

微信订阅号二维码如下:

这里写图片描述

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>

转载于:https://www.cnblogs.com/fengsehng/p/6048668.html

你可能感兴趣的文章
java 发展简史
查看>>
Js 数组排序函数sort()
查看>>
vtune 错误
查看>>
Sonya and Problem Wihtout a Legend CodeForces - 714E (dp)
查看>>
制作滑动门菜单
查看>>
jdk 8 新特性
查看>>
tomcat调优
查看>>
NameNode故障处理方法
查看>>
关于find的-perm
查看>>
修改pip默认安装目录
查看>>
[bzoj3073] Journeys 题解(线段树优化建图)
查看>>
vue中keepAlive的使用
查看>>
Oracle表空间、段、区和块简述
查看>>
Mysql数据库环境变量配置
查看>>
编程中经典语句
查看>>
bzoj3389
查看>>
生产环境 tomcat中启动缓慢
查看>>
【题解】Luogu P5290 [十二省联考2019]春节十二响
查看>>
linux中shell截取字符串方法总结
查看>>
BPM数据迁移
查看>>