From c2456ffe48743d6b480bfa4ae88c83b55eb43363 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 27 Mar 2024 10:46:20 +0800 Subject: [PATCH] 20240327 Finished --- src/problem/mod.rs | 3 +- ..._count_ways_to_group_overlapping_ranges.rs | 75 +++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 src/problem/p2580_count_ways_to_group_overlapping_ranges.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 98d971e..a7fe419 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -85,4 +85,5 @@ mod p2617_minimum_number_of_visited_cells_in_a_grid; mod p2549_count_distinct_numbers_on_board; mod p322_coin_change; mod p518_coin_change_ii; -mod p2642_design_graph_with_shortest_path_calculator; \ No newline at end of file +mod p2642_design_graph_with_shortest_path_calculator; +mod p2580_count_ways_to_group_overlapping_ranges; \ No newline at end of file diff --git a/src/problem/p2580_count_ways_to_group_overlapping_ranges.rs b/src/problem/p2580_count_ways_to_group_overlapping_ranges.rs new file mode 100644 index 0000000..6fcb840 --- /dev/null +++ b/src/problem/p2580_count_ways_to_group_overlapping_ranges.rs @@ -0,0 +1,75 @@ +/** + * [2580] Count Ways to Group Overlapping Ranges + */ +pub struct Solution {} + +// submission codes start here +struct Range { + start: i32, + end: i32, +} + +impl Solution { + pub fn count_ways(ranges: Vec>) -> i32 { + let mut ranges: Vec = ranges + .iter() + .map(|a| { + return Range { + start: a[0], + end: a[1], + }; + }) + .collect(); + + ranges.sort_unstable_by_key(|x| x.start); + + let mut merged_ranges = Vec::with_capacity(ranges.len()); + + let mut i = 0; + let mut last: Option<&mut Range> = None; + + while i < ranges.len() { + if let Some(last_range) = last { + while i < ranges.len() && last_range.end >= ranges[i].start { + last_range.end = last_range.end.max(ranges[i].end); + i += 1; + } + + if i >= ranges.len() { + break; + } + } + + merged_ranges.push(Range { + start: ranges[i].start, + end: ranges[i].end, + }); + last = merged_ranges.last_mut(); + i += 1; + } + + let mut result = 1; + + for _ in 0..merged_ranges.len() as i32 { + result = result * 2 % 1_000_000_007; + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2580() { + assert_eq!(2, Solution::count_ways(vec![vec![6, 10], vec![5, 15]])); + assert_eq!( + 4, + Solution::count_ways(vec![vec![1, 3], vec![10, 20], vec![2, 5], vec![4, 8]]) + ); + } +}