Skip to content

Commit

Permalink
impl summary ranges
Browse files Browse the repository at this point in the history
  • Loading branch information
SKTT1Ryze committed Apr 15, 2024
1 parent 3977411 commit 8f54606
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion leetcode-rs/src/solutions/summary_ranges.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::ops::Range;

use super::{test_helper, Solution};

pub struct SolutionImpl;
Expand All @@ -16,6 +18,34 @@ crate::derive_solution!(

impl SolutionImpl {
pub fn summary_ranges(nums: Vec<i32>) -> Vec<String> {
todo!()
if nums.is_empty() {
return vec![];
}
let mut ranges: Vec<Range<i32>> = Vec::new();
let mut start = nums[0];
let mut end = nums[0] + 1;

for num in nums.into_iter().skip(1) {
if num == end {
end += 1;
} else {
ranges.push(start..end);
start = num;
end = num + 1;
}
}

ranges.push(start..end);

ranges
.into_iter()
.map(|range| {
if range.len() == 1 || range.start == i32::MAX {
format!("{}", range.start)
} else {
format!("{}->{}", range.start, range.end - 1)
}
})
.collect()
}
}

0 comments on commit 8f54606

Please sign in to comment.