题目限制每条船只能载两个人,所以可以贪心。对people
进行排序,将最瘦的和最胖的组合,与limit
进行比较,若大于limit
,则最胖的需单独乘船,再将第二胖的与最瘦的组合,依次进行比较。
var numRescueBoats = function(people, limit) {
var count = 0
let thin = 0,
fat = people.length - 1;
people.sort((a, b) => a - b)
while (thin <= fat) {
if (people[thin] + people[fat] <= limit) {
thin++
}
fat--
count++
}
return count
};
复制代码
哈希集合存储一个链表,再遍历另一个链表,看节点是否存在哈希表中。
var getIntersectionNode = function(headA, headB) {
const visited = new Set();
let temp = headA;
while (temp !== null) {
visited.add(temp);
temp = temp.next;
}
temp = headB;
while (temp !== null) {
if (visited.has(temp)) {
return temp;
}
temp = temp.next;
}
return null;
};
复制代码
双指针,结束条件为链表第一次相交或者两个链表都遍历完。
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;
};
复制代码