From 1772ba6c996c5ba44e7393e437dc9fa3bdad686e Mon Sep 17 00:00:00 2001 From: li_chx Date: Mon, 2 Mar 2026 14:26:28 +0800 Subject: [PATCH] =?UTF-8?q?1536.=20=E6=8E=92=E5=B8=83=E4=BA=8C=E8=BF=9B?= =?UTF-8?q?=E5=88=B6=E7=BD=91=E6=A0=BC=E7=9A=84=E6=9C=80=E5=B0=91=E4=BA=A4?= =?UTF-8?q?=E6=8D=A2=E6=AC=A1=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 58 +++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 41 insertions(+), 17 deletions(-) diff --git a/src/main.rs b/src/main.rs index 129f0f3..fc9db41 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,26 +1,50 @@ -use std::cmp::Ordering; - struct Solution; mod arr; impl Solution { - pub fn sort_by_bits(arr: Vec) -> Vec { - let mut arr= arr.iter().map(|&x| ->(i32,i32){ - (x,x.count_ones() as i32) - }).collect::>(); - arr.sort_unstable_by(|a,b|-> Ordering { - let res = a.1.cmp(&b.1); - match res { - Ordering::Equal => a.0.cmp(&b.0), - _ => res, + 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; + } } - }); - arr.iter().map(|&(x,_)| x).collect() + cnt + } + let mut arr = Vec::::with_capacity(grid.len()); + for i in 0..grid[0].len() { + arr.push(count_tail_zero(&grid[i])) + } + 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; + } + } + cnt } } + fn main() { - let result = Solution::sort_by_bits( - vec![0,1,2,3,4,5,6,7,8] - ); + let result = Solution::min_swaps(arr::make_matrix( + "[[0,0,1],[1,1,0],[1,0,0]]", + )); println!("{:?}", result); -} \ No newline at end of file +}