分发糖果

135. 分发糖果

快手一面考过 — 要求常数时间复杂度

官方题解

nums   | 1 2 3  2 1
-----------------------
candy  | 1 2 3  2 1
candy' | 1 2 3  1 2

代码if dec == inc: dec += 1的作用体现在这:

nums   | 3 4 5  4 3 2 1
-----------------------
candy' | 1 2 5  4 3 2 1
candy  | 1 2 3  1 2 4 5
class Solution:
    def candy(self, ratings: List[int]) -> int:
        ret = 1
        dec = 0
        pre = 1
        inc = 1 # inc只在两个地方使用,一个是用来记录pre的值,一个是和dec进行比较
        N = len(ratings)
        for i in range(1, N):
            if ratings[i] >= ratings[i - 1]:
                # pre在【当前】<=【之前】的情况下会被重置为1
                pre = (1 if ratings[i] == ratings[i - 1] else pre + 1)
                dec = 0
                inc = pre
                ret += pre
            else:
                dec += 1
                if dec == inc:
                    dec += 1
                # pre在【当前】<=【之前】的情况下会被重置为1
                pre = 1
                ret += dec
        return ret
跳跃游戏

要求能背这两题

  • 基本题是贪心

55. 跳跃游戏

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        max_pos = 0
        n = len(nums)
        for i in range(n):
            if i > max_pos:
                return False
            max_pos = max(max_pos, i + nums[i])
        return True
  • 升级题还是贪心。。

45. 跳跃游戏 II

def jump(nums):
    ans = 0
    start = 0
    end = 1
    n = len(nums)
    while end < n:
        max_pos = 0
        for i in range(start, end):
            max_pos = max(max_pos, i + nums[i])
        start = end
        end = max_pos + 1
        ans += 1
    return ans
加油站

使用图的思想分析该问题

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        n = len(gas)
        min_spare = inf
        spare = 0
        pos = -1
        for i in range(n):
            spare += gas[i] - cost[i]
            if spare < min_spare:
                min_spare = spare
                pos = i
        return -1 if spare < 0 else (pos + 1) % n
划分字母区间

763. 划分字母区间

class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        last = {}
        for i, ch in enumerate(s):
            last[ch] = i
        
        partition = list()
        start = end = 0
        for i, ch in enumerate(s):
            end = max(end, last[ch])
            if i == end:
                partition.append(end - start + 1)
                start = end + 1 #别忘了 + 1
        
        return partition

种花问题

种花问题

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        N = len(flowerbed)

        def available(i):
            if flowerbed[i] == 0 and \
                    (i == 0 or flowerbed[i - 1] == 0) and \
                    (i == N - 1 or flowerbed[i + 1] == 0):
                return True
            return False

        cnt = 0
        for i in range(N):
            if available(i):
                cnt += 1
                flowerbed[i] = 1
                # print(i)
        return n <= cnt
根据身高重建队列

406. 根据身高重建队列

让高的排前面,矮的根据情况进行插队

身高:
3 4 5
前面比当前高的人数:
0 0 0 

根据【身高desc,人数asc】排序后按照【人数】为下标进行插入的过程:

[[5,0]]
[[4,0], [5,0]]
[[3,0], [4,0], [5,0]]

身高:
3 4 5 6
前面比当前高的人数:
0 0 1 0

根据【身高desc,人数asc】排序后按照【人数】为下标进行插入的过程:

[[6,0]]
[[6,0], [5,1]]
[[4,0], [6,0], [5,1]]
[[3,0], [4,0], [6,0], [5,1]]
class Solution:
    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        # 先按身高从高到低排序, 再按前面的人数从小到大排序
        people.sort(key=lambda x: (-x[0], x[1])) 
        n = len(people)
        ans = list()
        for person in people:
        	# 看似脱裤子放屁, 其实是防止数组越界错
        	# 用前面的人数作为下标,进行插入
            ans[person[1]:person[1]] = [person]
        return ans
单调递增的数字

738. 单调递增的数字

class Solution:
    def monotoneIncreasingDigits(self, n: int) -> int:
        ones = int('1' * 9)
        result = 0
        for _ in range(9):
            while ones + result > n:
                ones //= 10
            if ones == 0:
                break
            result += ones
        return result

Python3, 贪心,738

1234321
   ↑↑
   ji
1233999
---------
1444321
 ↑  ↑
 j  i
1399999
class Solution:
    def monotoneIncreasingDigits(self, n: int) -> int:
        s = list(str(n))
        L = len(s)
        found = False
        for i in range(1, L):
            # 第一个比【上个】元素小的
            if s[i] < s[i - 1]:
                found = True
                break
        if found:
            for j in range(i - 1, -1, -1):
                if not s[j] == s[j - 1]:
                    break
            s[j] = str(int(s[j]) - 1)
            for k in range(j + 1, L):
                s[k] = '9'
        return int(''.join(s))