Twice linear

题目

Consider a sequence u where u is defined as follows:

  1. The number u(0) = 1 is the first one in u.
  2. For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u too.
  3. There are no other numbers in u.

Ex: u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]

1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on…

Task:
Given parameter n the function dbl_linear (or dblLinear…) returns the element u(n) of the ordered (with <) sequence u (so, there are no duplicates).

Example:

should return 22```
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Note:
Focus attention on efficiency

### 分析
注重代码效率!
最终算法是通过比较大小,追踪最后一个生成的元素。生成到第```n```个时候输出。

### 答案
```javascript
function dblLinear(n) {
let arr = [1], y = 0, z = 0;
while (arr.length < n + 1) {
if (arr[y] * 2 + 1 < arr[z] * 3 + 1) {
arr.push(arr[y] * 2 + 1);
y++;
} else if (arr[y] * 2 + 1 > arr[z] * 3 + 1) {
arr.push(arr[z] * 3 + 1);
z++;
} else {
y++;
}
}
return arr[n];
}