|
| 1 | +# Problem: Summary Ranges |
| 2 | +# Link: https://leetcode.com/problems/summary-ranges/ |
| 3 | +# Tags: Array, Two Pointers |
| 4 | +# Approach: Track the start of each range, and whenever consecutive order breaks record the range and reset start; add the final range at the end. |
| 5 | +# Time Complexity: O(n) |
| 6 | +# Space Complexity: O(1) (excluding output) |
| 7 | + |
| 8 | + |
| 9 | +class Solution: |
| 10 | + def summaryRanges(self, nums): |
| 11 | + if not nums: |
| 12 | + return [] |
| 13 | + |
| 14 | + res = [] |
| 15 | + start = nums[0] |
| 16 | + |
| 17 | + for i in range(1, len(nums)): |
| 18 | + if nums[i] != nums[i-1] + 1: |
| 19 | + if start == nums[i-1]: |
| 20 | + res.append(str(start)) |
| 21 | + else: |
| 22 | + res.append(str(start) + "->" + str(nums[i-1])) |
| 23 | + start = nums[i] |
| 24 | + |
| 25 | + if start == nums[-1]: |
| 26 | + res.append(str(start)) |
| 27 | + else: |
| 28 | + res.append(str(start) + "->" + str(nums[-1])) |
| 29 | + |
| 30 | + return res |
0 commit comments