228.Summary Ranges
Tags: [string], [two_pointer]
Com: {g}
Link: https://leetcode.com/problems/summary-ranges/\#/description
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"].
Solution: Two Pointer
class Solution(object):
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
if not nums or len(nums) <= 1:
return [str(x) for x in nums]
size = len(nums)
result = []
start = 0
end = 1
while end < size:
if nums[end - 1] + 1 < nums[end]:
if start == end - 1:
result.append(str(nums[start]))
else:
result.append('{}->{}'.format(nums[start], nums[end - 1]))
start = end
end += 1
if start == end - 1:
result.append(str(nums[start]))
else:
result.append('{}->{}'.format(nums[start], nums[end - 1]))
return result
Note:
- Time complexity = O(n), n is the length of the given string.