You are given a string num, representing a large integer, and an integer
k.
We call some integer wonderful if it is a permutation of the digits in
num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones.
For example, when num = "5489355142":
The 1st smallest wonderful integer is "5489355214".
The 2nd smallest wonderful integer is "5489355241".
The 3rd smallest wonderful integer is "5489355412".
The 4th smallest wonderful integer is "5489355421".
Return _theminimum number of adjacent digit swaps that needs to be applied to _numto reach thekthsmallest wonderful integer.
The tests are generated in such a way that kth smallest wonderful integer exists.
Input: num ="5489355142", k =4Output: 2Explanation: The 4th smallest wonderful number is"5489355421". To get this number:- Swap index 7with index 8:"5489355 _14_ 2"->"5489355 _41_ 2"- Swap index 8with index 9:"54893554 _12_ "->"54893554 _21_ "
Input: num ="11112", k =4Output: 4Explanation: The 4th smallest wonderful number is"21111". To get this number:- Swap index 3with index 4:"111 _12_ "->"111 _21_ "- Swap index 2with index 3:"11 _12_ 1"->"11 _21_ 1"- Swap index 1with index 2:"1 _12_ 11"->"1 _21_ 11"- Swap index 0with index 1:"_12_ 111"->"_21_ 111"
Input: num ="00123", k =1Output: 1Explanation: The 1st smallest wonderful number is"00132". To get this number:- Swap index 3with index 4:"001 _23_ "->"001 _32_ "
To reach the kth smallest wonderful integer, we generate the next permutation k times. To count the minimum adjacent swaps needed to transform the original string into the target permutation, we use a greedy two-pointer approach: for each position, move the required digit to its place using adjacent swaps.
Generate the next permutation k times to get the target permutation.
For each position, if the digit differs from the original, find the position of the required digit and swap it leftwards using adjacent swaps, counting each swap.
impl Solution {
pubfnget_min_swaps(num: String, k: i32) -> i32 {
fnnext_perm(arr: &mut Vec<char>) {
let n = arr.len();
letmut i = n-2;
while i >=0&& arr[i] >= arr[i+1] {
if i ==0 { break; }
i -=1;
}
if i >=0 {
letmut j = n-1;
while arr[j] <= arr[i] { j -=1; }
arr.swap(i, j);
}
let (mut l, mut r) = (i+1, n-1);
while l < r {
arr.swap(l, r);
l +=1;
r -=1;
}
}
letmut arr: Vec<char>= num.chars().collect();
letmut target = arr.clone();
for _ in0..k { next_perm(&mut target); }
letmut ans =0;
for i in0..arr.len() {
if arr[i] != target[i] {
letmut j = i;
while arr[j] != target[i] { j +=1; }
while j > i {
arr.swap(j, j-1);
j -=1;
ans +=1;
}
}
}
ans
}
}