国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Leetcode: Intersection of Two Linked Lists

2019-11-14 22:19:14
字體:
來源:轉載
供稿:網友
Leetcode: Intersection of Two Linked Lists
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 }


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 英超| 法库县| 六盘水市| 余江县| 新化县| 开化县| 专栏| 精河县| 福建省| 缙云县| 南靖县| 汾西县| 吉林市| 榆林市| 麻江县| 乐安县| 永寿县| 武强县| 揭阳市| 建昌县| 诸城市| 兴宁市| 柳林县| 新巴尔虎右旗| 禹城市| 旺苍县| 静海县| 石门县| 娄底市| 余姚市| 从江县| 湖口县| 长岛县| 科技| 东安县| 容城县| 苍南县| 龙州县| 广东省| 凌云县| 应城市|