day31-greedy-part05-8.2

avatar
作者
猴君
阅读量:0

tasks for today

1. 56.合并区间

2. 738.单调递增的数字

3. 968.监控二叉树(optional)

----------------------------------------------------------------

1. 56.合并区间 In this practice, the mindset is similar to the practices in yesterday's tasks, but the difference is, in this practice, we do not aim to find the intersection, instead, we aim to find the combination, this is reflected on the operation of "min & max"
class Solution:     def merge(self, intervals: List[List[int]]) -> List[List[int]]:         intervals.sort(key = lambda x: (x[0], x[1]))         result = []         sl, sr = intervals[0][0], intervals[0][1]         for i in intervals:             if i[0] > sr:                 result.append([sl,sr])                 sl, sr = i[0], i[1]             else:                 sl = min(sl, i[0])                 sr = max(sr, i[1])                  result.append([sl, sr])                  return result

2. 738.单调递增的数字

In this practice, the key mindset is: if the digits[i] < digits[i-1], the digits[i-1] will be deduct 1, and the all rest digits from i on should be changed to 9.

class Solution:     def monotoneIncreasingDigits(self, n: int) -> int:         if n == 0: return 0         digits = [int(i) for i in str(n)]         for i in range(len(digits) - 1, 0, -1):             if digits[i] < digits[i - 1]:                 digits[i - 1] -= 1                 for k in range(i, len(digits)):                     digits[k] = 9         result = 0         for i in digits:             result = 10*result + i          return result

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!