Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6737705

Browse files
committed
Solve #228
1 parent fa5f01e commit 6737705

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

‎src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,3 +195,4 @@ mod n0224_basic_calculator;
195195
mod n0225_implement_stack_using_queues;
196196
mod n0226_invert_binary_tree;
197197
mod n0227_basic_calculator_ii;
198+
mod n0228_summary_ranges;

‎src/n0228_summary_ranges.rs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* [228] Summary Ranges
3+
*
4+
* Given a sorted integer array without duplicates, return the summary of its ranges.
5+
*
6+
* Example 1:
7+
*
8+
*
9+
* Input: [0,1,2,4,5,7]
10+
* Output: ["0->2","4->5","7"]
11+
* Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
12+
*
13+
*
14+
* Example 2:
15+
*
16+
*
17+
* Input: [0,2,3,4,6,8,9]
18+
* Output: ["0","2->4","6","8->9"]
19+
* Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
20+
*
21+
*
22+
*/
23+
pub struct Solution {}
24+
25+
// submission codes start here
26+
27+
impl Solution {
28+
pub fn summary_ranges(nums: Vec<i32>) -> Vec<String> {
29+
if nums.is_empty() { return vec![] }
30+
let mut res = Vec::new();
31+
let mut curr = nums[0];
32+
let mut start = nums[0];
33+
for num in nums.into_iter().skip(1) {
34+
if num == curr + 1 {
35+
curr = num;
36+
} else {
37+
// seq done
38+
Solution::record(&mut res, start, curr);
39+
start = num;
40+
curr = num;
41+
}
42+
}
43+
Solution::record(&mut res, start, curr);
44+
res
45+
}
46+
47+
pub fn record(vec: &mut Vec<String>, start: i32, end: i32) {
48+
if start == end {
49+
vec.push(format!("{}", start))
50+
} else {
51+
vec.push(format!("{}->{}", start, end))
52+
}
53+
}
54+
}
55+
56+
// submission codes end
57+
58+
#[cfg(test)]
59+
mod tests {
60+
use super::*;
61+
62+
#[test]
63+
fn test_228() {
64+
assert_eq!(Solution::summary_ranges(vec![0,1,2,3,4,5,6]), vec_string!["0->6"]);
65+
}
66+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /