[Leetcode] 228. Summary Ranges (Easy)

概述

題目

https://leetcode.com/problems/summary-ranges/
給出至多 20 個數,求其區間結果為何

心得

本題較為細碎,但實際小心判斷完即可 AC

Two Pointer

思路

前一指針 pre 表示上一次連續到現在的結果,後指針 go through 所有數字

程式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution(object):
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
# 長度為 0 或 1 之特例
if len(nums) == 0:
return []
elif len(nums) == 1:
return [str(nums[0])]

ret = []
pre = -1
for c in nums:
if c+1 not in nums:
if pre == -1:
ret.append(str(c))
else:
ret.append(str(pre)+"->"+str(c))
pre = -1
else:
if pre == -1:
pre = c

if pre == nums[-1]:
ret.append(str(c))
elif pre != -1:
ret.append(str(pre)+"->"+str(nums[-1]))
return ret

from StefanPochmann 大神

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
arr = []

for c in nums:
if not arr or c > arr[-1][-1] + 1:
arr.append([])
# arr += [],
arr[-1][1:] = [c]
# arr[-1][1:] = c,
return ["->".join(map(str, c)) for c in arr]

Complexity

Time Complexity: O(n)
最多走過一次 n 個數字

Space Complexity: O(n)
回傳至多 n 個區段結果