File tree Expand file tree Collapse file tree 2 files changed +11
-10
lines changed
src/problem_3107_minimum_operations_to_make_median_of_array_equal_to_k Expand file tree Collapse file tree 2 files changed +11
-10
lines changed Original file line number Diff line number Diff line change 1- pub mod greedy ;
1+ pub mod quick_select ;
22
33pub trait Solution {
44 fn min_operations_to_make_median_k ( nums : Vec < i32 > , k : i32 ) -> i64 ;
Original file line number Diff line number Diff line change @@ -3,6 +3,7 @@ pub struct Solution;
33// ------------------------------------------------------ snip ------------------------------------------------------ //
44
55use std:: cmp:: Ordering ;
6+ use std:: iter;
67
78impl Solution {
89 pub fn min_operations_to_make_median_k ( nums : Vec < i32 > , k : i32 ) -> i64 {
@@ -11,18 +12,18 @@ impl Solution {
1112
1213 nums. sort_unstable ( ) ;
1314
14- let middle = nums. len ( ) / 2 ;
15+ let half = nums. len ( ) / 2 ;
16+ let ( left, & mut middle, right) = nums. select_nth_unstable ( half) ;
1517
16- match nums [ middle] . cmp ( & k) {
17- Ordering :: Less => nums [ middle.. ]
18- . iter ( )
19- . map_while ( | & num| k . checked_sub ( num) . map ( i64 :: from ) )
18+ match middle. cmp ( & k) {
19+ Ordering :: Less => iter :: once ( middle)
20+ . chain ( right . iter ( ) . copied ( ) )
21+ . map ( | num| i64 :: from ( k . saturating_sub ( num) ) )
2022 . sum ( ) ,
2123 Ordering :: Equal => 0 ,
22- Ordering :: Greater => nums[ ..=middle]
23- . iter ( )
24- . rev ( )
25- . map_while ( |& num| num. checked_sub ( k) . map ( i64:: from) )
24+ Ordering :: Greater => iter:: once ( middle)
25+ . chain ( left. iter ( ) . copied ( ) )
26+ . map ( |num| i64:: from ( num. saturating_sub ( k) ) )
2627 . sum ( ) ,
2728 }
2829 }
You can’t perform that action at this time.
0 commit comments