comments | difficulty | edit_url | rating | source | tags | ||
---|---|---|---|---|---|---|---|
true |
Easy |
1365 |
Weekly Contest 288 Q1 |
|
You are given a positive integer num
. You may swap any two digits of num
that have the same parity (i.e. both odd digits or both even digits).
Return the largest possible value of num
after any number of swaps.
Example 1:
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.
Example 2:
Input: num = 65875 Output: 87655 Explanation: Swap the digit 8 with the digit 6, this results in the number 85675. Swap the first digit 5 with the digit 7, this results in the number 87655. Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.
Constraints:
1 <= num <= 109
We can use an array
Next, we traverse each digit of the integer
The time complexity is
class Solution:
def largestInteger(self, num: int) -> int:
nums = [int(c) for c in str(num)]
cnt = Counter(nums)
idx = [8, 9]
ans = 0
for x in nums:
while cnt[idx[x & 1]] == 0:
idx[x & 1] -= 2
ans = ans * 10 + idx[x & 1]
cnt[idx[x & 1]] -= 1
return ans
class Solution {
public int largestInteger(int num) {
char[] s = String.valueOf(num).toCharArray();
int[] cnt = new int[10];
for (char c : s) {
++cnt[c - '0'];
}
int[] idx = {8, 9};
int ans = 0;
for (char c : s) {
int x = c - '0';
while (cnt[idx[x & 1]] == 0) {
idx[x & 1] -= 2;
}
ans = ans * 10 + idx[x & 1];
cnt[idx[x & 1]]--;
}
return ans;
}
}
class Solution {
public:
int largestInteger(int num) {
string s = to_string(num);
int cnt[10] = {0};
for (char c : s) {
cnt[c - '0']++;
}
int idx[2] = {8, 9};
int ans = 0;
for (char c : s) {
int x = c - '0';
while (cnt[idx[x & 1]] == 0) {
idx[x & 1] -= 2;
}
ans = ans * 10 + idx[x & 1];
cnt[idx[x & 1]]--;
}
return ans;
}
};
func largestInteger(num int) int {
s := []byte(fmt.Sprint(num))
cnt := [10]int{}
for _, c := range s {
cnt[c-'0']++
}
idx := [2]int{8, 9}
ans := 0
for _, c := range s {
x := int(c - '0')
for cnt[idx[x&1]] == 0 {
idx[x&1] -= 2
}
ans = ans*10 + idx[x&1]
cnt[idx[x&1]]--
}
return ans
}
function largestInteger(num: number): number {
const s = num.toString().split('');
const cnt = Array(10).fill(0);
for (const c of s) {
cnt[+c]++;
}
const idx = [8, 9];
let ans = 0;
for (const c of s) {
const x = +c;
while (cnt[idx[x % 2]] === 0) {
idx[x % 2] -= 2;
}
ans = ans * 10 + idx[x % 2];
cnt[idx[x % 2]]--;
}
return ans;
}