You are given a sorted unique integer array nums
.
A range [a,b]
is the set of all integers from a
to b
(inclusive).
Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums
is covered by exactly one of the ranges, and there is no integer x
such that x
is in one of the ranges but not in nums
.
Each range [a,b]
in the list should be output as:
"a->b"
ifa != b
"a"
ifa == b
Example 1:
Input: nums = [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: The ranges are: [0,2] --> "0->2" [4,5] --> "4->5" [7,7] --> "7"
Example 2:
Input: nums = [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] Explanation: The ranges are: [0,0] --> "0" [2,4] --> "2->4" [6,6] --> "6" [8,9] --> "8->9"
Constraints:
0 <= nums.length <= 20
-231 <= nums[i] <= 231 - 1
- All the values of
nums
are unique. nums
is sorted in ascending order.
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
def make(nums, i, j):
return str(nums[i]) if i == j else f'{nums[i]}->{nums[j]}'
i = j = 0
n = len(nums)
res = []
while j < n:
while j + 1 < n and nums[j] + 1 == nums[j + 1]:
j += 1
res.append(make(nums, i, j))
i = j + 1
j = i
return res
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<>();
for (int i = 0, j = 0, n = nums.length; j < n;) {
while (j + 1 < n && nums[j] + 1 == nums[j + 1]) {
++j;
}
res.add(make(nums, i, j));
i = j + 1;
j = i;
}
return res;
}
private String make(int[] nums, int i, int j) {
return i == j ? String.valueOf(nums[i]) : String.format("%d->%d", nums[i], nums[j]);
}
}
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
for (int i = 0, j = 0, n = nums.size(); j < n;) {
while (j + 1 < n && nums[j] + 1 == nums[j + 1]) ++j;
res.push_back(make(nums, i, j));
i = j + 1;
j = i;
}
return res;
}
string make(vector<int>& nums, int i, int j) {
return i == j ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[j]);
}
};
func summaryRanges(nums []int) []string {
var res []string
for i, j, n := 0, 0, len(nums); j < n; {
for j+1 < n && nums[j]+1 == nums[j+1] {
j++
}
res = append(res, make(nums, i, j))
i = j + 1
j = i
}
return res
}
func make(nums []int, i, j int) string {
if i == j {
return strconv.Itoa(nums[i])
}
return strconv.Itoa(nums[i]) + "->" + strconv.Itoa(nums[j])
}
public class Solution {
public IList<string> SummaryRanges(int[] nums) {
var res = new List<string>();
for (int i = 0, j = 0, n = nums.Length; j < n;)
{
while (j + 1 < n && nums[j] + 1 == nums[j + 1])
{
++j;
}
res.Add(make(nums, i, j));
i = j + 1;
j = i;
}
return res;
}
public string make(int[] nums, int i, int j) {
return i == j ? nums[i].ToString() : string.Format("{0}->{1}", nums[i], nums[j]);
}
}