【无标题】一个题

无标题

There is an array generated by a rule:

  • The first item is 1.
  • If k is in the array, then k*3+1 and k*2+1 are in the array.
  • The array is sorted. There are no duplicate values.

Please write a function that accepts an input N . It should return the index N of the array.
For example [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ....]
n = 10 , return 22
n = 100 , return 447

// 起始数字为1,之后每个数字都是裂变成 两倍加1 和 三倍加1 两个数字。
const arr = [1];

let cache = [1]; // 减少裂变计算

const generate = (index) => {
    let stable = arr[index] && ((2 * cache[0] + 1) > arr[index]);

    while (arr.length < index + 1 || !stable) {
        console.log('计算');
        const newer = [];
        cache.forEach((n) => {
            const k2 = 2 * n + 1;
            const k3 = 3 * n + 1;
            // 不能有重复
            if (!arr.includes(k2) && !newer.includes(k2)) {
                newer.push(k2);
            }
            if (!arr.includes(k3) && !newer.includes(k3)) {
                newer.push(k3);
            }
        })

        arr.push(...newer); // 存入裂变出来的新数

        cache = newer.sort((a, b) => a - b); // 新数也是下一次裂变的基数
        arr.sort((a, b) => a - b); // 排序取目标值
        stable = !!arr[index] && ((2 * cache[0] + 1) > arr[index]); // 下一次裂变有可能产生比目标值更小的树,导致目标值改变
    }

    return arr[index];
}

console.log(generate(10));
console.log(generate(100));
console.log(generate(20));
console.log(arr);

暂记

你可能感兴趣的:(面试题,javascript,面试)