ID | Title | Difficulty | |
---|---|---|---|
Loading... |
228. Summary Ranges
Easy
LeetCode
Array
Problem
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
Code
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<>();
if(nums == null || nums.length == 0) return res;
for(int i = 0; i < nums.length; i++){
int num = nums[i];
while(i < nums.length - 1 && nums[i] + 1 == nums[i + 1]){
i++;
}
// 是一个范围
if(num != nums[i]){
res.add(num + "->" + nums[i]);
// 是一个数字
} else {
res.add(num + "");
}
}
return res;
}
}
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
if not nums:
return []
res = []
start = nums[0]
for i in range(1, len(nums)):
if nums[i] == nums[i - 1] + 1:
continue
if start == nums[i - 1]:
res.append(str(start))
else:
res.append(str(start) + "->" + str(nums[i - 1]))
start = nums[i]
if nums[-1] == start:
res.append(str(nums[-1]))
else:
res.append(str(start) + "->" + str(nums[-1]))
return res
按 <- 键看上一题!
227. Basic Calculator II
按 -> 键看下一题!
229. Majority Element II