#141 Linked list cycle
阿新 • • 發佈:2018-11-12
我的方法:用hashmap(可以過,但不是最佳)
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public boolean hasCycle(ListNode head) {14 Map<Integer, ListNode> map = new HashMap<>(); 15 ListNode current = head; 16 while(current != null){ 17 if(map.containsKey(current.val) && map.containsValue(current.next)){ 18 return true; 19 } 20 map.put(current.val, current.next);21 current = current.next; 22 } 23 return false; 24 } 25 }
基於我的方法上的優化:
1 public boolean hasCycle(ListNode head) { 2 Set<ListNode> nodesSeen = new HashSet<>(); 3 while (head != null) { 4 if (nodesSeen.contains(head)) { 5 returntrue; 6 } else { 7 nodesSeen.add(head); 8 } 9 head = head.next; 10 } 11 return false; 12 }
其實hashset和hashmap在map上沒什麼區別,hashset其實是在內部用了map。
hashtable, hashmap, hashset的區別: https://www.quora.com/What-is-the-difference-between-HashSet-HashMap-and-hash-table-How-do-they-behave-in-a-multi-threaded-environment
我可以優化的點:-- 關於同方法的程式碼簡化
1. 用current作為while的條件,而不是用current.next。這樣就可以省略最前面的null check。
2. 如果用map的話,要check有沒有key和value都在,實際上只要check當前node在不在就行了。可以直接把整個node塞進去。
3. 想太多,還要想next node的val。其實只要把ListNode看做一個整體進行操作就可以了。
Followup: Can you solve it without using extra space?