国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 梓潼县| 丹棱县| 禹城市| 扶绥县| 郁南县| 双桥区| 蓝田县| 平凉市| 巴彦县| 瓮安县| 大悟县| 武城县| 民勤县| 清苑县| 伊宁市| 毕节市| 巢湖市| 合水县| 绵阳市| 咸阳市| 建德市| 剑川县| 西乌珠穆沁旗| 沁阳市| 安康市| 新竹市| 隆尧县| 瑞金市| 顺昌县| 九江市| 金坛市| 尚义县| 清涧县| 新巴尔虎右旗| 巨野县| 大连市| 隆化县| 亚东县| 呼伦贝尔市| 阜宁县| 武强县|