Problem Solving
14. Summary Ranges
굥깡
2022. 9. 4. 02:30
728x90
https://leetcode.com/problems/summary-ranges/
Summary Ranges - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
리스트에서 이어지는 수끼리 토막 내서 작은 리스트들을 리턴
class Solution:
def summaryRanges(self, nums: list[int]) -> list[str]:
answer = []
if len(nums) == 0 or len(nums) == 1:
return map(str, nums)
count = nums[0]
start = nums[0]
flag = 0
for i in nums[1:]:
if i == count + 1:
if i == nums[-1]:
end = i
else:
count = count + 1
continue
else:
end = count
if i == nums[-1]:
flag = -1
if start == end:
element = str(start)
else:
element = str(start)+"->"+str(end)
answer.append(element)
start = i
count = i
if flag == -1:
answer.append(str(i))
return answer
뭔가 길어 보이는 건 경우의 수가 많아서 그런 거임ㅎㅎ....
[0,1,2,4,5,7]처럼 마지막 도막의 길이가 1인 경우를 처리하기 위해 flag를 넣음