34、相交連結串列
阿新 • • 發佈:2018-12-21
編寫一個程式,找到兩個單鏈表相交的起始節點。
例如,下面的兩個連結串列:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
在節點 c1 開始相交。
注意:
如果兩個連結串列沒有交點,返回 null.
在返回結果後,兩個連結串列仍須保持原有的結構。
可假定整個連結串列結構中沒有迴圈。
程式儘量滿足 O(n) 時間複雜度,且僅用 O(1) 記憶體。
一開始就是兩層迴圈進行,發現時間限制,之後根據提示可以用長度進行優化
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null){ return null; }else { ListNode list1 = headA; ListNode list2 = headB; int count1 = 0; int count2 = 0; while (list1 != null) { count1++; list1 = list1.next; } while (list2 != null) { count2++; list2 = list2.next; } int size = count1 > count2? count1 - count2: count2-count1; if(count1 > count2){ ListNode list3 = headA; ListNode list4 = headB; while (size > 0) { list3 = list3.next; size--; } while (list3!=null) { if(list3 == list4){ return list3; }else { list3 = list3.next; list4 = list4.next; } } }else { ListNode list3 = headA; ListNode list4 = headB; while (size > 0) { list4 = list4.next; size--; } while (list4!=null) { if(list3 == list4){ return list3; }else { list3 = list3.next; list4 = list4.next; } } } } return null; }
一次性成功的程式碼,這是頭一次,所以說思維清楚了程式碼也就很容易擼出來
排名比較高
貼出一個思路