Problem Description
2231. Largest Number After Digit Swaps by Parity
Analysis
This problem can be translated into:
- sort the even digits from big to small
- sort the odd digits from big to small
- combine them in the even odd order according to origin number
Because the digits can be sorted any time, not just once.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { public: int largestInteger(int num) { priority_queue<int> odds, even; vector<int> digits; while(num) { int digit = num % 10; if(digit & 1) { odds.push(digit); }else { even.push(digit); } digits.push_back(digit); num /= 10; } int sum = 0; for(int i = digits.size() - 1; i >= 0; i --) { sum *= 10; if(digits[i] & 1) { sum += odds.top(); odds.pop(); } else { sum += even.top(); even.pop(); } } return sum; } };
|
Author: o_oyao
License: All articles in this blog are licensed under
CC BY-NC-SA 4.0 unless stating additionally.