Problem : https://leetcode.com/problems/summary-ranges/
For number A, create the initial range [A, A]. If the next number B = A + 1, then extends the range as [A, B]. Otherwise create new initial range [B, B] and append to the result list.
Time Complexity = O ( N )
Space Complexity = O ( N )
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
result = []
for n in nums:
if result and n == result[-1][1] + 1:
result[-1][1] = n
else:
result.append([n, n])
return ["{}->{}".format(a, b) if a != b else "{}".format(a) for a, b in result]
No comments:
Post a Comment