Solution 1 - Two Pointer Iteration
Walk the array and expand each consecutive run into a range string.
Walk the array and expand each consecutive run into a range string.
""" 0228.1 - Summary Ranges - Solution 1 - Two Pointer Iteration """
#####################################################################################
# Imports
#####################################################################################
from typing import List
#####################################################################################
# Classes
#####################################################################################
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
res: List[str] = []
i = 0
n = len(nums)
while i < n:
start = nums[i]
while i + 1 < n and nums[i + 1] == nums[i] + 1:
i += 1
end = nums[i]
res.append(str(start) if start == end else f"{start}->{end}")
i += 1
return respackage main
import "fmt"
func summaryRanges(nums []int) []string {
out := []string{}
for i := 0; i < len(nums); i++ {
start := nums[i]
for i+1 < len(nums) && nums[i+1] == nums[i]+1 {
i++
}
end := nums[i]
if start == end {
out = append(out, fmt.Sprintf("%d", start))
} else {
out = append(out, fmt.Sprintf("%d->%d", start, end))
}
}
return out
}
func main() {}fn summary_ranges(nums: &[i32]) -> Vec<String> {
let mut res: Vec<String> = vec![];
let mut i: usize = 0;
while i < nums.len() {
let start = nums[i];
while i + 1 < nums.len() && nums[i + 1] == nums[i] + 1 {
i += 1;
}
let end = nums[i];
if start == end {
res.push(start.to_string());
} else {
res.push(format!("{}->{}", start, end));
}
i += 1;
}
res
}
fn main() {}