1545. 找出第 N 个二进制字符串中的第 K 位
This commit is contained in:
parent
1772ba6c99
commit
563c0b3589
66
src/main.rs
66
src/main.rs
|
|
@ -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;
|
||||
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';
|
||||
}
|
||||
if k == len / 2 + 1 {
|
||||
return '1';
|
||||
}
|
||||
if k > len / 2 + 1 {
|
||||
if Self::find_kth_bit(n - 1, (len / 2+1) - (k - (len / 2 + 1))) == '1' {
|
||||
'0'
|
||||
} else {
|
||||
return cnt;
|
||||
'1'
|
||||
}
|
||||
} else {
|
||||
Self::find_kth_bit(n - 1, k)
|
||||
}
|
||||
}
|
||||
cnt
|
||||
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);
|
||||
}
|
||||
let mut arr = Vec::<i32>::with_capacity(grid.len());
|
||||
for i in 0..grid[0].len() {
|
||||
arr.push(count_tail_zero(&grid[i]))
|
||||
*value = Some(arr);
|
||||
}
|
||||
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 cant{
|
||||
return -1;
|
||||
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);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue