File tree 2 files changed +39
-9
lines changed
2 files changed +39
-9
lines changed Original file line number Diff line number Diff line change 3
3
* @return {boolean }
4
4
*/
5
5
var isHappy = function ( n ) {
6
- // 用哈希集合检测循环
7
-
8
6
// 获取下一个数
9
7
const getNext = ( num ) => {
10
8
let sum = 0 ;
@@ -15,7 +13,10 @@ var isHappy = function (n) {
15
13
}
16
14
return sum ;
17
15
} ;
16
+
17
+ // 用哈希集合检测循环
18
18
const set = new Set ( ) ;
19
+
19
20
while ( n !== 1 && ! set . has ( n ) ) {
20
21
set . add ( n ) ;
21
22
n = getNext ( n ) ;
Original file line number Diff line number Diff line change 13
13
* @return {ListNode }
14
14
*/
15
15
var getIntersectionNode = function ( headA , headB ) {
16
+ // 思路: 让 headA 和 headB 从同一起点出来, 开始移动, 结果 相交或不相交
17
+ // 这种方式更好理解
18
+
16
19
if ( ! headA || ! headB ) {
17
20
return null ;
18
21
}
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 ) ;
19
34
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 ;
26
45
}
46
+ return headA ;
27
47
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;
29
58
} ;
You can’t perform that action at this time.
0 commit comments