Skip to content

Commit 593cef8

Browse files
committed
Merge branch 'main' of github.com:w2xi/leetcode
2 parents 45fc3f9 + fdcd6ea commit 593cef8

File tree

2 files changed

+39
-9
lines changed

2 files changed

+39
-9
lines changed

algorithms/happy-number.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
* @return {boolean}
44
*/
55
var isHappy = function (n) {
6-
// 用哈希集合检测循环
7-
86
// 获取下一个数
97
const getNext = (num) => {
108
let sum = 0;
@@ -15,7 +13,10 @@ var isHappy = function (n) {
1513
}
1614
return sum;
1715
};
16+
17+
// 用哈希集合检测循环
1818
const set = new Set();
19+
1920
while (n !== 1 && !set.has(n)) {
2021
set.add(n);
2122
n = getNext(n);

algorithms/intersection-of-two-linked-lists.js

+36-7
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,46 @@
1313
* @return {ListNode}
1414
*/
1515
var getIntersectionNode = function (headA, headB) {
16+
// 思路: 让 headA 和 headB 从同一起点出来, 开始移动, 结果 相交或不相交
17+
// 这种方式更好理解
18+
1619
if (!headA || !headB) {
1720
return null;
1821
}
22+
const getLength = (head) => {
23+
let count = 0;
24+
let curr = head;
25+
while (curr) {
26+
count++;
27+
curr = curr.next;
28+
}
29+
return count;
30+
};
31+
let aLen = getLength(headA);
32+
let bLen = getLength(headB);
33+
let diff = Math.abs(aLen - bLen);
1934

20-
let currA = headA;
21-
let currB = headB;
22-
23-
while (currA !== currB) {
24-
currA = currA ? currA.next : headB;
25-
currB = currB ? currB.next : headA;
35+
if (aLen < bLen) {
36+
[headA, headB] = [headB, headA];
37+
[aLen, bLen] = [bLen, aLen];
38+
}
39+
while (diff--) {
40+
headA = headA.next;
41+
}
42+
while (headA !== headB) {
43+
headA = headA.next;
44+
headB = headB.next;
2645
}
46+
return headA;
2747

28-
return currA;
48+
// if (!headA || !headB) {
49+
// return null;
50+
// }
51+
// let currA = headA;
52+
// let currB = headB;
53+
// while (currA !== currB) {
54+
// currA = currA ? currA.next : headB;
55+
// currB = currB ? currB.next : headA;
56+
// }
57+
// return currA;
2958
};

0 commit comments

Comments
 (0)