1545. 找出第 N 个二进制字符串中的第 K 位
This commit is contained in:
parent
1772ba6c99
commit
563c0b3589
70
src/main.rs
70
src/main.rs
|
|
@ -1,50 +1,48 @@
|
||||||
|
use std::cell::RefCell;
|
||||||
|
|
||||||
struct Solution;
|
struct Solution;
|
||||||
mod arr;
|
mod arr;
|
||||||
|
|
||||||
impl Solution {
|
impl Solution {
|
||||||
pub fn min_swaps(grid: Vec<Vec<i32>>) -> i32 {
|
pub fn find_kth_bit(n: i32,mut k: i32) -> char {
|
||||||
fn count_tail_zero(arr: &Vec<i32>) -> i32 {
|
let len = Self::get_length_arr()(n);
|
||||||
let mut cnt = 0;
|
if n == 1 || k == 0 {
|
||||||
for i in (0..arr.len()).rev() {
|
return '0';
|
||||||
if arr[i] == 0 {
|
|
||||||
cnt += 1;
|
|
||||||
} else {
|
|
||||||
return cnt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
cnt
|
|
||||||
}
|
}
|
||||||
let mut arr = Vec::<i32>::with_capacity(grid.len());
|
if k == len / 2 + 1 {
|
||||||
for i in 0..grid[0].len() {
|
return '1';
|
||||||
arr.push(count_tail_zero(&grid[i]))
|
|
||||||
}
|
}
|
||||||
let mut cnt = 0;
|
if k > len / 2 + 1 {
|
||||||
for i in (0..grid.len()).rev() {
|
if Self::find_kth_bit(n - 1, (len / 2+1) - (k - (len / 2 + 1))) == '1' {
|
||||||
let mut index = 0;
|
'0'
|
||||||
let mut cant = true;
|
} else {
|
||||||
for j in 0..arr.len() {
|
'1'
|
||||||
if arr[j] == -1 {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if arr[j] >= i as i32 {
|
|
||||||
arr[j] = -1;
|
|
||||||
cnt += index;
|
|
||||||
cant = false;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
index += 1;
|
|
||||||
}
|
}
|
||||||
if cant{
|
} else {
|
||||||
return -1;
|
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() {
|
fn main() {
|
||||||
let result = Solution::min_swaps(arr::make_matrix(
|
let result = Solution::find_kth_bit(4, 14);
|
||||||
"[[0,0,1],[1,1,0],[1,0,0]]",
|
|
||||||
));
|
|
||||||
println!("{:?}", result);
|
println!("{:?}", result);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue