Sponsored
Sponsored
This approach involves detecting the start and end of each range by iterating through the array sequentially. You remember the start of a potential range and adjust the range's end as long as consecutive numbers are found. When a break in consecutiveness occurs, you fix the end of the current range and start a new one.
Time Complexity: O(n)
Space Complexity: O(n)
1
2#include <vector>
3#include <string>
4
5using namespace std;
6
7vector<string> summaryRanges(vector<int>& nums) {
8 vector<string> result;
9 int n = nums.size();
10 int i = 0;
11 while (i < n) {
12 int start = i;
13 while (i + 1 < n && nums[i] + 1 == nums[i + 1]) {
14 i++;
15 }
16 if (start == i) {
17 result.push_back(to_string(nums[start]));
18 } else {
19 result.push_back(to_string(nums[start]) + "->" + to_string(nums[i]));
20 }
21 i++;
22 }
23 return result;
24}
25
The C++ solution follows a similar logic as the C code. It uses iterators to find ranges of consecutive numbers. It appends ranges (or single numbers) to the result list in string format, making use of STL's string and vector facilities.
This approach utilizes a two-pointer method where one pointer marks the beginning of a new range, and another pointer (or the loop index itself) expands the range as far as possible until the next number isn't consecutive. Once a sequence ends, if numbers are the same, it is a single-element range; otherwise, a range connecting two different numbers is formed.
Time Complexity: O(n)
Space Complexity: O(n)
1using System;
using System.Collections.Generic;
public class Solution {
public IList<string> SummaryRanges(int[] nums) {
List<string> result = new List<string>();
int i = 0;
while (i < nums.Length) {
int start = i;
int j = i;
while (j + 1 < nums.Length && nums[j] + 1 == nums[j + 1]) {
j++;
}
if (start == j) {
result.Add(nums[start].ToString());
} else {
result.Add(nums[start] + "->" + nums[j]);
}
i = j + 1;
}
return result;
}
}
The C# solution employs two pointers approach, where the first pointer marks a new range beginning, while the second loop adjusts as numbers follow each other. This method yields consistent performance and clarity.