廣州做網站哪家專業(yè)最近三天的新聞大事國內
文章目錄
- 題目
- 方法一:哈希表set去重
- 方法二:快慢指針
題目
方法一:哈希表set去重
思路:我們遍歷鏈表中的每個節(jié)點,并將它記錄下來;一旦遇到了此前遍歷過的節(jié)點,就可以判定鏈表中存在環(huán)。借助哈希表可以很方便地實現。
public ListNode detectCycle(ListNode head) {if(head == null) return null;if(head.next==null) return null;if(head.next.next == head) return head;Set<ListNode> NodeSet = new HashSet<>();while(head != null){if(NodeSet.add(head)){head =head.next;continue;}else return head;}return null;}
方法二:快慢指針
第一次快慢指針相遇后。馬上讓新指針ptr從head 和slow同步走,最終會在環(huán)點相遇
public ListNode detectCycle(ListNode head) {if (head == null) return null;ListNode fast = head;//快指針ListNode slow = head;//慢指針while(fast!=null){//滿足快指針不空指針異常(fast.next.next!=null)//移動指針slow = slow.next;if(fast.next !=null) fast = fast.next.next;else return null;if(fast==slow) {//說明一定有環(huán)了ListNode ptr = head;//定義新指針從head出發(fā)while(ptr != slow){ptr = ptr.next;slow = slow.next;}return ptr;}}return null;}