Skip to main content

leetCode

https://leetcode.com/

Hard

Medium

Add two Numbers

note

因为这道题的入参和出参都是要求为 ListNode 格式, 但是实现起来以数组的方式好实现,所以就有一个 arr2ListNodeListNode2Arr 的转换。 要注意一下题目的注释里写了链表的值,key 为val而不是value 还有一个坑是,这里涉及到大数的计算,所以在做加法的时候需要考虑一些极限情况 关于 ListNode 的解释可以看这里 // TODO: 待补充

testcase
const plus1 = [
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1,
];
const plus2 = [5, 6, 4];
const ListNode2Arr = (listNode) => {
if (!listNode) {
return [];
}
const arr = [listNode.val];
const restArr = ListNode2Arr(listNode.next);
return arr.concat(restArr);
};

const arr2ListNode = (arr) => {
if (!arr.length) {
return null;
}
const head = { val: arr[0], next: null };
let preNode = head;
for (let i = 1; i < arr.length; i++) {
const curNode = { val: arr[i], next: null };
preNode.next = curNode;
preNode = curNode;
}
return head;
};

const addTwoNumbers = function (l1, l2) {
const arrReverse = (arr) => arr.map(arr.pop, [...arr]);
const getPlus = (arr) =>
arr.reduce(
(pre, cur, index, origin) =>
pre + BigInt(cur) * BigInt(10) ** BigInt(origin.length - index - 1),
BigInt(0)
);
const reverse1 = arrReverse(ListNode2Arr(l1));
const reverse2 = arrReverse(ListNode2Arr(l2));
const plus1 = getPlus(reverse1);
const plus2 = getPlus(reverse2);
const res = arrReverse(`${plus1 + plus2}`.split('')).map((item) =>
Number(item)
);
console.log({
list2arr: ListNode2Arr(l1),
reverse1,
reverse2,
plus1,
plus2,
res1111: res,
});
return arr2ListNode(res);
};

Easy

Two sum

const twoSum = function (nums, target) {
for (let i = 0; i < nums.length; i++) {
const res = nums.find((item) => item === target - nums[i]);
if (typeof res === 'number' && i !== nums.lastIndexOf(res)) {
return [i, nums.lastIndexOf(res)];
}
}
};
console.log(twoSum([3, 2, 4], 6));