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 +}