回家续上刷题,题目集LeetCode 热题100
160. 相交链表
最笨的办法,挨个查
var getIntersectionNode = function(headA, headB) {
let temp = headA;
while(temp !==null) {
let temp2 = headB
let interval = null
while(temp2!== null) {
if(temp==temp2) {
interval = temp2
break;
}
temp2 = temp2.next
}
if(interval) {
return interval
}
temp = temp.next
}
return null
};
利用哈希表,判断内部是否有重合
/**
* 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 list = new Set();
let temp1 = headA;
while(temp1!=null) {
list.add(temp1)
temp1 = temp1.next
}
let temp2 = headB;
while(temp2!=null){
if(list.has(temp2)){
return temp2
}
temp2 = temp2.next
}
return null
};
学习到一个新的解决两个链表长度不一样的遍历方法
案例 headA=[1,9,1,2,4] headB=[3,2,4]==>headB只有3个元素,3个元素遍历完 headB=[1,9,1,2,4] headA=[2,4]==>headA遍历完headA=[3,2,4] headB=[1,2,4] 按正常条件判断第二个元素条件满足跳出循环
var getIntersectionNode = function(headA, headB) {
if (headA === null || headB === null) {
return null;
}
let pA = headA, pB = headB;
while (pA !== pB) {
pA = pA === null ? headB : pA.next;
pB = pB === null ? headA : pB.next;
}
return pA;
};
滴滴面试题
上一年滴滴一面有一个手写题:‘判断链表是不是环’,这个题目跟160相似
206、反转链表
var reverseList = function(head) {
let resover = null
let cur=head
while(cur){
const next =cur.next
cur.next = resover
resover=cur
cur=next
}
return resover
};
经典面试题 2、两数相加
涉及进位问题
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let head = null, tail = null;
let carry = 0;
while (l1 || l2) {
const n1 = l1 ? l1.val : 0;
const n2 = l2 ? l2.val : 0;
const sum = n1 + n2 + carry;
if (!head) {
head = tail = new ListNode(sum % 10);
} else {
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
carry = Math.floor(sum / 10);
if (l1) {
l1 = l1.next;
}
if (l2) {
l2 = l2.next;
}
}
if (carry > 0) {
tail.next = new ListNode(carry);
}
return head;
};
146LRU
这个也是一个遇见过一次面试出的手写题,力扣的这个算一个简易版的LRU缓存实现,以前就应该多刷刷力扣,呜呜🥹