https://leetcode.com/problems/summary-ranges/?envType=study-plan-v2&envId=top-interview-150
Summary Ranges - LeetCode
Can you solve this real interview question? Summary Ranges - You are given a sorted unique integer array nums. A range [a,b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the arr
leetcode.com
전체 코드
# 1:52 ~ 2:17 (25")
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
if not nums:
return []
tmp_answer = []
pre = nums[0]
tmp = [pre]
for i in range(1, len(nums)):
if (pre + 1) == nums[i]:
pre = nums[i]
tmp.append(nums[i])
else:
tmp_answer.append(tmp)
pre = nums[i]
tmp = [pre]
tmp_answer.append(tmp)
answer = []
for a in tmp_answer:
if len(a) == 1:
answer.append(str(a[0]))
else:
answer.append(str(a[0])+"->"+str(a[-1]))
return answer
'Coding Test > Python' 카테고리의 다른 글
[LeetCode] 215. Kth Largest Element in an Array(medium, python) (0) | 2024.01.05 |
---|---|
[백준] 16236번: 아기 상어 (골드3, 파이썬) (0) | 2024.01.04 |
[백준] 15686번: 치킨 배달(골드5, 파이썬) (0) | 2024.01.04 |
[LeetCode] 199. Binary Tree Right Side View (medium, python) (0) | 2024.01.03 |
[LeetCode] 2. Add Two Numbers (medium, python) (0) | 2024.01.03 |