[LeetCode] #141 環形連結串列
阿新 • • 發佈:2021-08-16
[LeetCode] #141 環形連結串列
給定一個連結串列,判斷連結串列中是否有環。
如果連結串列中有某個節點,可以通過連續跟蹤 next 指標再次到達,則連結串列中存在環。 為了表示給定連結串列中的環,我們使用整數 pos 來表示連結串列尾連線到連結串列中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該連結串列中沒有環。注意:pos 不作為引數進行傳遞,僅僅是為了標識連結串列的實際情況。
如果連結串列中存在環,則返回 true 。 否則,返回 false 。
輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:連結串列中有一個環,其尾部連線到第二個節點。
HashSet是不允許有重複元素的集合,可以利用其性質完成這道題。
public class Solution { public boolean hasCycle(ListNode head) { Set<ListNode> node = new HashSet<ListNode>(); while (head != null) { if (!node.add(head)) { return true; } head = head.next; } returnfalse; } }
也可以用快慢指標實現
public class Solution { public boolean hasCycle(ListNode head) { if (head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while (slow != fast) { if (fast == null|| fast.next == null) { return false; } slow = slow.next; fast = fast.next.next; } return true; } }
知識點:
HashSet不能新增重複的元素,當呼叫add(Object)方法時候,如果元素不存在則插入並返回true,存在則直接返回false
總結:無