860、柠檬水找零:
class Solution(object):def lemonadeChange(self, bills):""":type bills: List[int]:rtype: bool"""five, ten = 0, 0for i in range(len(bills)):if bills[i] == 5:five += 1elif bills[i] == 10:if five == 0:return Falsefive -= 1ten += 1elif bills[i] == 20:if ten > 0 and five > 0:five -= 1ten -= 1elif five >= 3:five -= 3else:return Falsereturn True
本题是模拟类型题,需要找准局部最优策略即可解决
406、根据身高重建队列:
class Solution(object):def reconstructQueue(self, people):""":type people: List[List[int]]:rtype: List[List[int]]"""people = sorted(people, key=lambda x: (x[0], -x[1]), reverse=True)res = []for i in range(len(people)):position = people[i][1]if position == i:res.append(people[i])else:res.insert(position, people[i])return res
本题需要从两个维度考虑,先考虑身高维度,进行逆序排序,再考虑数量维度,对遍历的元素进行判断插入,妙处在于对身高进行逆序排序,这样后续操作时不会影响前面已操作元素
452、用最少数量的箭引爆气球:
class Solution(object):def findMinArrowShots(self, points):""":type points: List[List[int]]:rtype: int"""points = sorted(points, key=lambda x: (x[0], x[1]), reverse=False)res = 1for i in range(1, len(points)):if points[i][0] <= points[i-1][1]:points[i][1] = min(points[i][1], points[i-1][1])else:res += 1return res
本题比较简单,因为需要把区间相邻的气球放在一起,所以要先进行排序,然后遍历过程中不断更新公共区间