写法一:维护right和left两个数作为当前区间的左右边界
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key = lambda x: x[0])
left = intervals[0][0]
right = intervals[0][1]
res = []
for i in range(1, len(intervals)):
if intervals[i][0] > right:
res.append([left, right])
left = intervals[i][0]
right = intervals[i][1]
else:
right = max(right, intervals[i][1])
res.append([left, right])
return res
写法二:修改res末尾区间的右边界直到它不与当前区间重合,将这个不重合的新区间推入res。
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key = lambda x: x[0])
res = []
res.append(intervals[0])
for i in range(1, len(intervals)):
if res[-1][1] < intervals[i][0]:
res.append(intervals[i])
else:
res[-1][1] = max(res[-1][1], intervals[i][1])
return res
关键在于从后往前遍历,一旦遇到反单调递增的数就用flag记下其位置,同时前一个数减去1。退出循环后,从flag开始(包括flag)都改为9,flag以前的数按digit数组。
class Solution:
def monotoneIncreasingDigits(self, n: int) -> int:
if 0 <= n <= 9:
return n
digit = []
tmp = n
while tmp > 0:
digit.insert(0, tmp % 10)
tmp //= 10
flag = len(digit)
for i in range(len(digit)-1, 0, -1):
if digit[i-1] > digit[i]:
flag = i
digit[i-1] -= 1
res = 0
for i in range(flag):
res = res * 10 + digit[i]
for i in range(flag, len(digit)):
res = res * 10 + 9
return res