java: add «2191. Sort the Jumbled Numbers»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-07-24 13:28:21 +02:00
parent 8caa3ec8bd
commit 4cf960b73b
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,35 @@
class Solution {
private class Jumble {
public int original;
public int mapped;
public Jumble(int[] mapping, int original) {
this.original = original;
map(mapping, original);
}
private void map(int[] mapping, int original) {
mapped = mapping[original % 10];
original /= 10;
for (int power = 10; original > 0; power *= 10, original /= 10) {
mapped += power * mapping[original % 10];
}
}
}
public int[] sortJumbled(int[] mapping, int[] nums) {
var jumbled = new Jumble[nums.length];
for (int i = 0; i < nums.length; ++i) {
jumbled[i] = new Jumble(mapping, nums[i]);
}
Arrays.sort(jumbled, Comparator.comparing(k -> ((Jumble) k).mapped));
for (int i = 0; i < nums.length; ++i) {
nums[i] = jumbled[i].original;
}
return nums;
}
}