1. 문제
2. 나의 풀이
2-1. for문으로 문제 풀기
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
result = []
if len(nums) < 1:
return result
a = nums[0]
b = nums[0]
for i in range(len(nums)):
b = nums[i]
current_num = nums[i]
if i >= (len(nums) -1):
if (a == b):
result.append(str(a))
else:
result.append(str(a)+"->"+str(b))
break
next_num = nums[i+1]
if abs(next_num - current_num) > 1:
if a == b:
result.append(str(a))
else:
result.append(str(a)+"->"+str(b))
a = nums[i+1]
return result
2-2. 코드를 예쁘게 바꿔보기
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
result = []
if len(nums) < 1:
return result
a = nums[0]
b = nums[0]
prev_num = nums[0]
for i in range(1, len(nums)):
current_num = nums[i]
if abs(current_num - prev_num) > 1:
new_range = F'{str(a)}->{str(b)}' if a!=b else str(a)
result.append(new_range)
a = nums[i]
prev_num = nums[i]
b = nums[i]
new_range = F'{str(a)}->{str(b)}' if a!=b else str(a)
result.append(new_range)
return result
3. Reference