Maximum number that can be formed from the given digits

前端 未结 2 330
执笔经年
执笔经年 2021-01-16 14:25

Given a Integer, find the maximum number that can be formed from the digits. Input : 8754365 output : 8765543

I told solution in $O(n logn)$. He asked me optimize

2条回答
  •  逝去的感伤
    2021-01-16 15:09

    The following greedy code does this in O(n) time. Where n is the number of digits in the number.

    int num = 8756404;
    int[] times = new int[10];
    while(true){
        if(num==0){
            break;
        }
        int val = num%10;
        times[val]++;
        num /= 10;
    }
    for(int i=9; i>=0; i--){
        for(int j=0; j

    It works by counting the number of occurences of each of the digits in the input number. Then printing each number the number of times it was in the input number in reverse order, ie. starting from 9 to 0.

提交回复
热议问题