|
| 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