zoukankan      html  css  js  c++  java
  • 刷题160. Intersection of Two Linked Lists

    一、题目说明

    题目160. Intersection of Two Linked Lists,计算两个链表相连的位置。难度是Easy!

    二、我的解答

    这个题目,简单思考一下还是容易的。一次遍历,找到ListA、ListB的最后一个元素及其长度,如果endA==endB则相交。先移动长链表的指针abs(numA-numB),然后找到相等的位置即可。

    代码如下:

    class Solution{
    	public:
    		ListNode* getIntersectionNode(ListNode* headA, ListNode* headB){
    			if(headA==NULL || headB==NULL) return NULL;
    			ListNode* endA = headA,*endB=headB;
    			int numA = 1,numB = 1;
    			
    			//find the last element of headA
    			while(endA->next !=NULL){
    				endA = endA->next;
    				numA++;
    			}
    			
    			//find the last element of headB
    			while(endB->next !=NULL){
    				endB = endB->next;
    				numB++;
    			}
    			if(endA != endB){
    				return NULL;
    			}else{
    				endA = headA;
    				endB = headB;
    				if(numA>numB){
    					int t = numA-numB;
    					while(t>0){
    						endA = endA->next;
    						t--;
    					}
    				}else if(numA<numB){
    					int t = numB-numA;
    					while(t>0){
    						endB = endB->next;
    						t--;
    					}
    				}
    				
    				while(endA != endB){
    					endA = endA->next;
    					endB = endB->next;
    				}
    				return endA;
    			}
    		}
    };
    

    性能如下:

    Runtime: 44 ms, faster than 96.04% of C++ online submissions for Intersection of Two Linked Lists.
    Memory Usage: 16.9 MB, less than 59.26% of C++ online submissions for Intersection of Two Linked Lists.
    

    三、优化措施

    可以继续优化,但意义不大。

    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    数组中找出最小的K个数
    温故而知新---Java(一)
    写一手简洁的代码
    同步IO与同步非阻塞IO的理解
    旋转打印矩阵
    求仅出现一次的最早字符
    spring 自定义schema 加载异常 White spaces are required between publicId and systemId.
    Java位运算知识点整理
    Idea 插件开发之DubboInvoke实践
    pinpoint插件开发实践
  • 原文地址:https://www.cnblogs.com/siweihz/p/12275870.html
Copyright © 2011-2022 走看看