1545. 找出第 N 个二进制字符串中的第 K 位

This commit is contained in:
li_chx 2026-03-03 09:30:37 +08:00
parent 1772ba6c99
commit 563c0b3589
Signed by: li_chx
GPG Key ID: 70D4985BB8180E92
1 changed files with 34 additions and 36 deletions

View File

@ -1,50 +1,48 @@
use std::cell::RefCell;
struct Solution;
mod arr;
impl Solution {
pub fn min_swaps(grid: Vec<Vec<i32>>) -> i32 {
fn count_tail_zero(arr: &Vec<i32>) -> i32 {
let mut cnt = 0;
for i in (0..arr.len()).rev() {
if arr[i] == 0 {
cnt += 1;
} else {
return cnt;
}
}
cnt
pub fn find_kth_bit(n: i32,mut k: i32) -> char {
let len = Self::get_length_arr()(n);
if n == 1 || k == 0 {
return '0';
}
let mut arr = Vec::<i32>::with_capacity(grid.len());
for i in 0..grid[0].len() {
arr.push(count_tail_zero(&grid[i]))
if k == len / 2 + 1 {
return '1';
}
let mut cnt = 0;
for i in (0..grid.len()).rev() {
let mut index = 0;
let mut cant = true;
for j in 0..arr.len() {
if arr[j] == -1 {
continue;
}
if arr[j] >= i as i32 {
arr[j] = -1;
cnt += index;
cant = false;
break;
}
index += 1;
if k > len / 2 + 1 {
if Self::find_kth_bit(n - 1, (len / 2+1) - (k - (len / 2 + 1))) == '1' {
'0'
} else {
'1'
}
if cant{
return -1;
} else {
Self::find_kth_bit(n - 1, k)
}
}
fn get_length_arr() -> impl Fn(i32) -> i32 {
let cell = RefCell::new(None);
move |n| {
let mut value = cell.borrow_mut();
if value.is_none() {
let mut arr = Vec::with_capacity(20);
arr.push(1);
for _ in 1..20 {
arr.push(arr[arr.len() - 1] * 2 + 1);
}
*value = Some(arr);
}
if let Some(x) = value.as_ref() {
x[n as usize - 1]
} else {
0
}
}
cnt
}
}
fn main() {
let result = Solution::min_swaps(arr::make_matrix(
"[[0,0,1],[1,1,0],[1,0,0]]",
));
let result = Solution::find_kth_bit(4, 14);
println!("{:?}", result);
}