Write a PRogram to find the node at which the intersection of two singly linked lists begins.For example, the following two linked lists:A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3begin to intersect at node c1.Notes:If the two linked lists have no intersection at all, return null.The linked lists must retain their original structure after the function returns.You may assume there are no cycles anywhere in the entire linked structure.Your code should preferably run in O(n) time and use only O(1) memory.
第一想法是用HashSet<ListNode>, A list先遍歷,存HashSet,然后B list遍歷,發現ListNode存在就返回。但是這個方法不滿足O(1)memory的要求。
再想了一會兒,略微受了點提醒,發現可以利用這個O(n) time做文章。這個條件方便我們scan list幾次都可以。于是我想到了:
先scan A list, 記錄A list長度lenA, 再scan B list, 記錄B list長度lenB. 看A list最后一個元素與 B list最后一個元素是否相同就可以知道是否intersect.
各自cursor回到各自list的開頭,長的那個list的cursor先走|lenA - lenB|步,然后一起走,相遇的那一點就是所求
1 /** 2 * Definition for singly-linked list. 3 * public 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 ListNode getIntersectionNode(ListNode headA, ListNode headB) {14 if (headA==null || headB==null) return null;15 int lenA = 1;16 int lenB = 1;17 ListNode cursorA = headA;18 ListNode cursorB = headB;19 while (cursorA.next != null) {20 lenA++;21 cursorA = cursorA.next;22 }23 while (cursorB.next != null) {24 lenB++;25 cursorB = cursorB.next;26 }27 if (cursorA != cursorB) return null;28 cursorA = headA;29 cursorB = headB;30 if (lenA - lenB >= 0) {31 for (int i=0; i<lenA-lenB; i++) {32 cursorA = cursorA.next;33 }34 }35 else {36 for (int j=0; j<lenB-lenA; j++) {37 cursorB = cursorB.next;38 }39 }40 while (cursorA != cursorB) {41 cursorA = cursorA.next;42 cursorB = cursorB.next;43 }44 return cursorA;45 }46 }
新聞熱點
疑難解答