Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f963396

Browse files
Create summary_ranges.py
1 parent 56ec01c commit f963396

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎day-29/summary_ranges.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /