晴明的博客园 GitHub      CodePen      CodeWars     

[js] 连续补充数组重排序

#

            function dblLinear(n) {
                var temp = [1];
                var y = 0,
                    z = 0,
                    j = 0,
                    k = 0,
                    i = 0;
                while (i < n) {
                    y = temp[i] * 2 + 1;
                    z = temp[i] * 3 + 1;
                    for (j = temp.length - 1; j > -1; j--) {
                        if (y == temp[j]) {
                            break;
                        }
                        if (y > temp[j]) {
                            temp.splice(j + 1, 0, y);
                            break;
                        }
                    }
                    for (k = temp.length - 1; k > -1; k--) {
                        if (z == temp[k]) {
                            break;
                        }
                        if (z > temp[k]) {
                            temp.splice(k + 1, 0, z);
                            break;
                        }
                    }
                    i++;
                }
                return temp[n];
            }
            console.log(dblLinear(0));
            console.log(dblLinear(10));
            console.log(dblLinear(20));
            console.log(dblLinear(30));
            console.log(dblLinear(50));
            console.log(dblLinear(100));
            console.log(dblLinear(200));
            console.log(dblLinear(500));
            console.log(dblLinear(1000));
            console.log(dblLinear(2000));
            console.log(dblLinear(5000));
            console.log(dblLinear(6000));
            console.log(dblLinear(10000));

 

#

            function dblLinear(n) {
                var ai = 0,
                    bi = 0,
                    eq = 0;
                var sequence = [1];
                while (ai + bi < n + eq) {
                    var y = 2 * sequence[ai] + 1;
                    var z = 3 * sequence[bi] + 1;
                    if (y < z) {
                        sequence.push(y);
                        ai++;
                    } else if (y > z) {
                        sequence.push(z);
                        bi++;
                    } else {
                        sequence.push(y);
                        ai++;
                        bi++;
                        eq++;
                    }
                }
                return sequence.pop();
            }

 

posted @ 2016-04-05 15:07  晴明桑  阅读(516)  评论(0编辑  收藏  举报