ORIGIN

LeetCode 2231. Largest Number After Digit Swaps by Parity

ACM 1 min142 words

Problem Description

2231. Largest Number After Digit Swaps by Parity

Analysis

This problem can be translated into:

  1. sort the even digits from big to small
  2. sort the odd digits from big to small
  3. 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;
}
};
TOP
COMMENT
  • ABOUT
  • |
o_oyao
  The Jigsaw puzzle is incomplete with even one missing piece. And I want to be the last piece to make the puzzle complete.
Like my post?
Default QR Code
made with ❤️ by o_oyao
©o_oyao 2019-2024

|