国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

[LeetCode] Linked List Cycle

2019-11-15 01:11:54
字體:
來源:轉載
供稿:網(wǎng)友
[LeetCode] Linked List Cycle

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

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

關于cycle,第一個想法自然就是用hashmap來做。注意用hashmap.put()method的時候,value隨便設置一個數(shù)就可以了。

因為我們只是檢測key是否有重復的,value在這里的意義不大。

代碼如下。~

/** * 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) {        HashMap<ListNode,Integer> hash=new HashMap<ListNode,Integer>();        if(head==null){            return false;        }        while(head!=null){            if(hash.containsKey(head)){                return true;            }            hash.put(head,1);            head=head.next;        }        return false;    }}

但是再看一下follow up那里要求的是without extra space,那么這樣的話hashmap就暫時不能用了。

用two pointer來做就可以了。快慢指針。(fase/slow) (fast每次走兩步,slow則是一步。)

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


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 郑州市| 建宁县| 汝阳县| 旌德县| 公主岭市| 贵定县| 连城县| 铁力市| 梁河县| 和顺县| 威宁| 栖霞市| 宣武区| 湾仔区| 修武县| 如东县| 晋城| 江津市| 玛多县| 双江| 日喀则市| 神池县| 襄汾县| 博白县| 巨野县| 汝城县| 阳谷县| 通城县| 温州市| 徐水县| 高陵县| 化隆| 屏南县| 尼勒克县| 肥西县| 碌曲县| 霍州市| 杭州市| 双鸭山市| 册亨县| 萨迦县|