相交链表(leetcode)

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {

struct ListNode* pf = headA;

struct ListNode* pd;

struct ListNode* str;

int i = 0;

while( pf != NULL )

{

for( pd = headB ; pd != NULL ; pd = pd->next )

{

if( pf == pd )

{

for( str = pf ; pd != NULL ; pd = pd->next , str = str->next )

{

if( str == pd )

{

;

}

else

goto end;

}

if( str == NULL )

return pd;

}

end:

}

pf = pf->next;

}

return NULL;

}

由于使用了三层循环嵌套:导致时间复杂度O(n^3)过高

改进:

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {

struct ListNode *a = headA;

struct ListNode *b = headB;

struct ListNode *shortnode;

struct ListNode *longnode;

int len_a = 1;

int len_b = 1;

int i = 0;

while( a->next != NULL )

{

a = a->next;

len_a++;

}

while( b->next != NULL )

{

b = b->next;

len_b++;

}

if( a == b )

{

if( len_a > len_b )

{

shortnode = headB;

longnode = headA;

}

else

{

shortnode = headA;

longnode = headB;

}

for( i = 0 ; i < abs(len_a-len_b) ; i++)

{

longnode = longnode->nest;

}

while( longnode != shortnode )

{

longnode = longnode->next;

shortnode = shortnode->next;

}

return longnode;

}

else

{

return NULL;

}

}

时间复杂度:O(n);

相关推荐
橘子汽水16814 小时前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
Re.不晚17 小时前
挑战做100道力扣算法- DAY1
算法·leetcode·职场和发展
青山木18 小时前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
星轨初途21 小时前
LeetCode 热题 100——day2 字母异位词分组
c++·算法·leetcode
Livia要学习21 小时前
Python2和Python3字典底层原理
数据结构
青梅橘子皮1 天前
STL---map/set... “家族“详解(从使用到底层)(1)
数据结构·算法
Adios7941 天前
搜索二维矩阵 II
java·数据结构·算法
雪碧聊技术1 天前
力扣 72. 编辑距离——动态规划经典例题
算法·leetcode·动态规划
木井巳1 天前
【DFS解决floodfill算法】岛屿的最大面积
java·算法·leetcode·深度优先
Tisfy1 天前
LeetCode 1406.石子游戏 III:递归(DFS+记忆化) / 递推(DP+原地滚动)
leetcode·游戏·深度优先·dfs·题解·博弈