java: add «2191. Sort the Jumbled Numbers»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
8caa3ec8bd
commit
4cf960b73b
1 changed files with 35 additions and 0 deletions
35
java/sort-the-jumbled-numbers.java
Normal file
35
java/sort-the-jumbled-numbers.java
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue