Leetcode - 2231. Largest Number After Digit Swaps by Parity


質問する


与えられた整数値が次の条件を満たす場合、swapは最大数に変換されます.
  • の各ビット数は、偶数または奇数の間でのみ交換できます.
  • https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/
    Input: num = 1234
    Output: 3412
    Explanation: Swap the digit 3 with the digit 1, this results in the number 3214.
    Swap the digit 2 with the digit 4, this results in the number 3412.
    Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.
    Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.

    解決する


    貪欲に解決する.最初のビット数を最大値に変換し、前のビット数が最大値であることを保証できます.
    O(N^2)
    void swap(char arr[], int a, int b)
    {
        char temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
    /* '0' ~ '9' -> 48 ~ 57 */
    bool compare(char a, char b)
    {
        int ap = a % 2;
        int bp = b % 2;
        if (ap != bp)
            return false;
        if (a > b)
            return true;
        else
            return false;    
    }
    void greedy(char arr[], int size)
    {
        for (int st_idx = 0; st_idx < size - 1; st_idx++) {
            for (int i = st_idx + 1; i < size; i++) {
                if (compare(arr[i], arr[st_idx]))
                    swap(arr, i, st_idx);
            }
        }
    }
    int largestInteger(int num){
        int ret = 0, size = 0;
        char arr[11] = {0,};
        
        sprintf(arr, "%d", num);
        size = strlen(arr);
        greedy(arr, size);
        sscanf(arr, "%d", &ret);
        return ret;
    }