leetcode 算法题160 (简单038) 相交链表

leetcode 算法题160 (简单038) 相交链表

  • 题目介绍
编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
在节点 c1 开始相交。

  • 示例

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 输出:Reference of the node with value = 8 输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。 来源:力扣(LeetCode)
输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 输出:Reference of the node with value = 2 输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。

  • 解法一
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function(headA, headB) {
  let tempA = [], tempB = [], i = 0;
  while(headA) {
    tempA.push(headA);
    headA = headA.next;
  }
  while(headB) {
    tempB.push(headB);
    headB = headB.next;
  }
  while(i < Math.min(tempA.length , tempB.length) && tempA[tempA.length - 1 - i] === tempB[tempB.length - 1 - i]) {
    i++;
  }
  return i === 0 ? null : tempA[tempA.length - i];
};

执行用时 : 116 ms, 在所有 JavaScript 提交中击败了88.77%的用户

内存消耗 : 42.7 MB, 在所有 JavaScript 提交中击败了70.68%的用户

  • 解法二
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function(headA, headB) {
  let tempA = [],
    tempB = [],
    i = 0;
  while (headA) {
    tempA.push(headA);
    headA = headA.next;
  }
  while (headB) {
    if(tempA.indexOf(headB) > - 1) {
      return headB;
    }
    headB = headB.next;
  }
  return null;
};

执行用时 : 300 ms, 在所有 JavaScript 提交中击败了7.55%的用户

内存消耗 : 43.3 MB, 在所有 JavaScript 提交中击败了30.89%的用户

  • 解法三

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */


/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function(headA, headB) {
  let pointA = headA,
    pointB = headB,
    flagA = true,
    flagB = true;
  while (pointA && pointB) {
    if (pointA === pointB) {
      return pointA;
    }
    if (pointA.next) {
      pointA = pointA.next
    } else {
      if (flagA) {
        pointA = headB;
        flagA = false;
      } else {
        return null;
      }
    }
    if (pointB.next) {
      pointB = pointB.next;
    } else {
      if (flagB) {
        pointB = headA;
        flagB = false;
      } else {
        return null;
      }
    }
  }
  return null;
};

执行用时 : 124 ms, 在所有 JavaScript 提交中击败了69.61%的用户

内存消耗 : 42.9 MB, 在所有 JavaScript 提交中击败了51.31%的用户

上一篇:手写防抖节流函数


下一篇:038.[转] JVM启动过程与类加载