Leetcode[228] Summary Ranges
29 Nov 2015###Task1 Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7], return [“0->2”,”4->5”,”7”].
###Python ####Mine
class Solution(object):
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
if not nums or len(nums) == 0:
return []
cur = str(nums[0])
prev = nums[0]
ret = []
for i in range(1, len(nums)):
if nums[i] == prev + 1:
prev += 1
continue
else:
if int(cur) != prev:
cur += '->'
cur += str(prev)
ret.append(cur)
prev = nums[i]
cur = str(nums[i])
if int(cur) != prev:
cur += '->'
cur += str(prev)
ret.append(cur)
return ret
####Short but robust
class Solution:
# @param {integer[]} nums
# @return {string[]}
def summaryRanges(self, nums):
x, size = 0, len(nums)
ans = []
while x < size:
c, r = x, str(nums[x])
while x + 1 < size and nums[x + 1] - nums[x] == 1:
x += 1
if x > c:
r += "->" + str(nums[x])
ans.append(r)
x += 1
return ans
###Java
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<String>();
if (nums == null || nums.length == 0) {
return res;
}
if (nums.length == 1) {
res.add(String.valueOf(nums[0]));
return res;
}
int start = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i - 1] + 1) {
StringBuilder sb = new StringBuilder();
sb.append(start);
if (start != nums[i - 1]) {
sb.append("->");
sb.append(nums[i - 1]);
}
res.add(sb.toString());
start = nums[i];
}
}
StringBuilder sb = new StringBuilder();
sb.append(start);
if (start != nums[nums.length - 1]) {
sb.append("->");
sb.append(nums[nums.length - 1]);
}
res.add(sb.toString());
return res;
}
}
###Points
- O(n)