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
2import java.util.ArrayList;
3import java.util.List;
4
5public class Solution {
6 public List<String> summaryRanges(int[] nums) {
7 List<String> result = new ArrayList<>();
8 int i = 0;
9 while (i < nums.length) {
10 int start = i;
11 while (i + 1 < nums.length && nums[i] + 1 == nums[i + 1]) {
12 i++;
13 }
14 if (start == i) {
15 result.add(String.valueOf(nums[start]));
16 } else {
17 result.add(nums[start] + "->" + nums[i]);
18 }
19 i++;
20 }
21 return result;
22 }
23}
24
In the Java solution, we maintain a list to store the ranges. We track the beginning and end of each consecutive sequence of numbers and convert the range to the required string format when a sequence ends or we reach the list's end.
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)
1
#include <vector>
#include <string>
using namespace std;
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result;
int n = nums.size();
int i = 0;
while (i < n) {
int start = i;
int j = i;
while (j + 1 < n && nums[j] + 1 == nums[j + 1]) {
j++;
}
if (start == j) {
result.push_back(to_string(nums[start]));
} else {
result.push_back(to_string(nums[start]) + "->" + to_string(nums[j]));
}
i = j + 1;
}
return result;
}
In C++, a nested loop designates two pointers to start and expand through the array, denoting where numbers are not consecutive anymore. It uses the starting and ending pointers to create a string of the range.