From 563c0b35898637d7f6376a43d4c745de747ab91f Mon Sep 17 00:00:00 2001 From: li_chx Date: Tue, 3 Mar 2026 09:30:37 +0800 Subject: [PATCH] =?UTF-8?q?1545.=20=E6=89=BE=E5=87=BA=E7=AC=AC=20N=20?= =?UTF-8?q?=E4=B8=AA=E4=BA=8C=E8=BF=9B=E5=88=B6=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?=E4=B8=AD=E7=9A=84=E7=AC=AC=20K=20=E4=BD=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 70 ++++++++++++++++++++++++++--------------------------- 1 file changed, 34 insertions(+), 36 deletions(-) diff --git a/src/main.rs b/src/main.rs index fc9db41..f016ff4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,50 +1,48 @@ +use std::cell::RefCell; + struct Solution; mod arr; - impl Solution { - pub fn min_swaps(grid: Vec>) -> i32 { - fn count_tail_zero(arr: &Vec) -> 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::::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); }