1、c++
(1)不考虑空间复杂度,也就是不是使用O(1)内存,使用了额外的辅助空间,时间复杂度也不是O(N)
就是把链表A的节点放入set容器中,遍历链表B,链表B中第一个出现在set容器中的节点就是所求的交点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
std::set<ListNode*> node_set;
while(headA){//将链表A中的节点插入set容器中,注意插入的是指针地址
node_set.insert(headA);
headA=headA->next;
}
while(headB){
if(node_set.find(headB)!=node_set.end()){
//find会挨个查找set,当到达set.end()时,也就是一个也没找到,返回end
//所以感觉不如hash函数,hash函数就不会从头开始找
return headB;
}
headB=headB->next;
}
return NULL;
}
};
上面还是用hash会更好,因为set的find函数还是从头找,不如hash省时间。
(2)c++解法2 考虑时间复杂度
非常直观的思路
直接看两个链表的长度差,让长链表先走长度差的距离,让长短链表长度一样的时候,开始进行比较。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int lengthA=0,lengthB=0;
ListNode *tempA=headA;
ListNode *tempB=headB;
while(headA){
lengthA++;
headA=headA->next;
}
while(headB){
lengthB++;
headB=headB->next;
}
int move=0;
if(lengthA>lengthB){
move=lengthA-lengthB;
while(move--){
tempA=tempA->next;
}
}
else{
move=lengthB-lengthA;
while(move--){
tempB=tempB->next;
}
}
while(tempA){
if(tempA==tempB){
return tempA;
}
else{
tempA=tempA->next;
tempB=tempB->next;
}
}
return NULL;
}
};
java代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lengthA=0,lengthB=0;
ListNode tempA=headA;
ListNode tempB=headB;
while(headA!=null){
lengthA++;
headA=headA.next;
}
while(headB!=null){
lengthB++;
headB=headB.next;
}
int move=0;
boolean flag=true;
if(lengthB>lengthA){
flag=false;
move=lengthB-lengthA;
}
else{
move=lengthA-lengthB;
}
if(flag){
while(move!=0){
tempA=tempA.next;
move--;
}
}
else{
while(move!=0){
tempB=tempB.next;
move--;
}
}
while(tempA!=null){
if(tempA==tempB){
return tempA;
}
else{
tempA=tempA.next;
tempB=tempB.next;
}
}
return null;
}
}
java和c++还是有细微熵的一定要注意的
c++ while(head) while(move)
而java while(head!=null) while(move!=0)