Skip to content

Commit af540a8

Browse files
committed
Refactor
1 parent 88decb9 commit af540a8

File tree

2 files changed

+11
-10
lines changed

2 files changed

+11
-10
lines changed

src/problem_3107_minimum_operations_to_make_median_of_array_equal_to_k/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
pub mod greedy;
1+
pub mod quick_select;
22

33
pub trait Solution {
44
fn min_operations_to_make_median_k(nums: Vec<i32>, k: i32) -> i64;

src/problem_3107_minimum_operations_to_make_median_of_array_equal_to_k/greedy.rs renamed to src/problem_3107_minimum_operations_to_make_median_of_array_equal_to_k/quick_select.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ pub struct Solution;
33
// ------------------------------------------------------ snip ------------------------------------------------------ //
44

55
use std::cmp::Ordering;
6+
use std::iter;
67

78
impl 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
}

0 commit comments

Comments
 (0)