麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

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

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 }


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 曰韩毛片 | 久久国产精品影视 | 爱射av | 综合网天天射 | 国产91对白叫床清晰播放 | 香蕉久草视频 | 中文字幕免费在线观看视频 | 成人男女啪啪免费观看网站四虎 | 一级黄色欧美 | 日本中文字幕久久 | 91成人亚洲| 久久久久久久久久久久久久av | 91精品国产综合久久婷婷香蕉 | 欧美在线观看视频一区 | 欧美 日韩 国产 在线 | 黄色一级片在线免费观看 | 高清成人在线 | xxxx18韩国护士hd老师 | 视频一区 中文字幕 | 欧美人与牲禽动交精品一区 | 在线观看国产免费视频 | 日本成人二区 | 精品亚洲va在线va天堂资源站 | 中文字幕 亚洲一区 | 久久精品国产一区二区电影 | 美女亚洲 | 亚洲操比视频 | 美国av片在线观看 | 亚洲视屏在线 | 成人国产精品一区二区毛片在线 | 国产一区二区免费看 | 午夜视频播放 | 欧美黑大粗硬毛片视频 | 国产99视频在线观看 | 久久欧美亚洲另类专区91大神 | 国产精品色在线网站 | 一边吃奶一边插下面 | 国产精品亚洲三区 | 黄网站免费在线看 | 日韩av电影在线免费观看 | 免费的性爱视频 |