# LeetCode 109

## Description

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

## Solution

1. 将链表转换成数组

数组定位中点的效率是$O(1)$，所以算法复杂度是$O(N)$，但是需要$O(N)$的额外空间。

2. 直接在链表上做

链表定位中点的效率是$O(N)$，所以算法复杂度是$O(N\log N)$，只需要$O(1)$的辅助空间。

Python Code：

# LeetCode 142

## Description

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

Example 1:

Example 2:

Example 3:

Can you solve it without using extra space?

## Solution

$$\frac{A + B + k_1 C}{2} = \frac{A + B + k_2 C}{1}$$

$$(k_1 - 2k_2)C = A + B$$

1. 若$C > A$，那么显然解是$k_1 = 1, k_2 = 0, B = C - A$。
2. 若$C \leq A$，那么显然解是$k_2 = 0, k_1 = \lfloor \frac{A}{C}\rfloor, B = A \mod C$。

$$A = (C - B) + (k_1 - 2k_2 - 1)C$$

CPP Code：

------ 本文结束------
0%