141.Linked List Cycle
阿新 • • 發佈:2017-10-18
pre hash get 利用 lap 兩個指針 leetcode span opened
題目鏈接:https://leetcode.com/problems/linked-list-cycle/description/
題目大意:給出一個鏈表,判斷該鏈表是否有環,空間復雜度最好控制在o(1)
這個題沒有給測試用例,導致沒太明白題目意思,看了題解,用了兩種方法示例如下:
法一(借鑒):利用兩個指針,一個指針步長為2,一個指針步長為1,若鏈表中有環,則兩個指針同時走,在某一時刻一定會走到一起;若鏈表中沒有環,則兩個指針一定會走到null,代碼如下(耗時1ms):
1 public boolean hasCycle(ListNode head) { 2 ListNode fast = head;View Code3 ListNode slow = head; 4 while(fast != null && slow != null && fast.next != null) { 5 slow = slow.next; 6 fast = fast.next.next; 7 if(slow == fast) { 8 return true; 9 } 10 } 11 returnfalse;
法二(借鑒):利用set集合中的contains,判斷是否有兩個相同的結點在集合中,如果有,則有環,代碼如下(耗時10ms):
1 Set<ListNode> list = new HashSet<>(); 2 while(head != null) { 3 if(list.contains(head)) { 4 return true; 5 } 6 else { 7 list.add(head);View Code8 head = head.next; 9 } 10 } 11 return false;
141.Linked List Cycle