Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

混杂整数序列按规则进行重新排序 #34

Open
Rain120 opened this issue Mar 28, 2022 · 1 comment
Open

混杂整数序列按规则进行重新排序 #34

Rain120 opened this issue Mar 28, 2022 · 1 comment

Comments

@Rain120
Copy link
Owner

Rain120 commented Mar 28, 2022

题目

假设我们取一个数字 x 并执行以下任一操作:

a: 将 x 除以 3 (如果可以被 3 除)
b: 将 x 乘以 2
每次操作后,记下结果。如果从 9 开始,可以得到一个序列

有一个混杂的整数序列,现在任务是对它们重新排序,以使其符合上述序列并输出结果

输入: "[4,8,6,3,12,9]"
输出: [9,3,6,12,4,8]

解释: [9,3,6,12,4,8] => 9/3=3 -> 3*2=6 -> 6*2=12 -> 12/3=4 -> 4*2=8

输入: "[3000,9000]"
输出: [9000,3000]

输入: "[4,2]"
输出: [2,4]

输入: "[4,6,2]"
输出: [6,2,4]
function changeArr(arr) {
  // ...
}
@Rain120
Copy link
Owner Author

Rain120 commented Mar 28, 2022

对数组重新排序,使得数组每一项可以满足这样一个规则:arr[i] = arr[i + 1] * 3 或者 arr[i] = arr[i + 1] / 2

function changeArr(arr) {
    const map = new Map();
    let res;

    arr.forEach(n => {
        map.set(n, (map.get(n) || 0) + 1);
    });

    const dfs = (prev, index, cur) => {
        if (index === arr.length + 1) {
            res = cur;
            return;
        }

        if (map.get(prev * 2) > 0) {
            const value = prev * 2;
            map.set(value, map.get(value) - 1);
            dfs(value, index + 1, [...cur, value]);
            map.set(value, map.get(value) + 1);
        }

        if (!(prev % 3) && map.get(prev / 3) > 0) {
            const value = prev / 3
            map.set(value, map.get(value) - 1);
            dfs(value, index + 1, [...cur, value]);
            map.set(value, map.get(value) + 1);
        }
    }

    arr.forEach(n => {
        dfs(n, 2, [n]);
    });

    return res;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant