題意:求兩個單向鍊錶的交點。要求時間複雜度為o(n),空間複雜度為o(1)。答案如下
#include
#include
using namespace std;
//definition for singly-linked list.
struct listnode ;
};//方法一:unordered_map,時間複雜度滿足要求,但空間複雜度不滿足o(1)的要求
class solution );
heada = heada->next;
}if (headb)
);headb = headb->next;}}
return nullptr;}};
//方法二:great!網友方法《真正符合題意時間複雜度o(n)【3*n,4*n,常數*n,複雜度都是o(n)】,空間複雜度為o(1)【同理常數空間複雜度都是o(1)】>
//分別先將兩鍊錶遍歷一次,得到各自的count,然後count多的鍊錶作移動,直到兩鍊錶長度一致,再同步遍歷。
class solution
if (ptra)
}else
}while (heada && headb)
return nullptr;}};
Leetcode解題思路
所有簡單題的解題思路。question count the number of prime numbers less than a non negative number,n example input 10output 4explanation there are 4 prime numbers ...
LeetCode160 相交鍊錶
編寫乙個程式,找到兩個單鏈表相交的起始節點。例如,下面的兩個鍊錶 在節點 c1 開始相交。注意 如果兩個鍊錶沒有交點,返回 null.在返回結果後,兩個鍊錶仍須保持原有的結構。可假定整個鍊錶結構中沒有迴圈。程式盡量滿足 o n 時間複雜度,且僅用 o 1 記憶體。解題思路 1.找到兩個鍊錶長度差n後...
Leetcode160 相交鍊錶
解法一 用乙個集合去判斷 class solution sets listnode tmp1 heada listnode tmp2 headb while tmp1 while tmp2 tmp2 tmp2 next return nullptr 解法二 先遍歷一遍兩個鍊錶得到的長度差n,然後讓長...