贪心专题2 - leetcode452. 用最少数量的箭引爆气球/406.根据身高重建队列 - Mark

452. Minimum Number of Arrows to Burst Balloons

题目描述

在二维空间有许多球形气球。对每个气球,输入是水平方向上气球直径的开始和结束坐标(开始坐标总是小于结束坐标)。

记一个气球直径的开始和结束坐标为 xstart,xend。在坐标x处射出一支箭,若 xstart ≤ x ≤ xend,则该气球会被引爆。
可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。
求所需弓箭的最小数量,使所有气球都被引爆。

例子

Input: [[10,16], [2,8], [1,6], [7,12]]
Output: 2
Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).

思想
和重叠区间有关~
首先区间按start排序;依次遍历区间,若两区间重叠,记录重叠区域;然后判断下一个区间是否和该重叠区域重合。若重合,继续记录重叠区域;否则弓箭数+1。
(改进)
按end排序

解法

class Solution(object):
    def findMinArrowShots(self, points):
        """
        :type points: List[List[int]]
        :rtype: int
        """
        if not points:
            return 0
        
        cnt = 1
        points = sorted(points, key = lambda x:x[0])
        end = points[0][1]
        for point in points[1:]:
            if end >= point[0]:    # overlap
                end = min(end, point[1])
            else:
                end = point[1]
                cnt += 1
        return cnt

改进:按end排序

class Solution(object):
    def findMinArrowShots(self, points):
        """
        :type points: List[List[int]]
        :rtype: int
        """
        points = sorted(points, key = lambda x:x[1])
        cnt = 0
        end = float('-inf')
        for point in points:
            if point[0] > end:    # non-overlap
                cnt += 1
                end = point[1]
        return cnt
406. Queue Reconstruction by Height

题目描述

假设有打乱顺序的一群人站成一个队列。
每人用一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面即身高≥h的人数。
编写一个算法来重建这个队列。

例子

Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
Output: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

思想
要点是排序方式。
1)按照h降序,k升序的方式排列。例子为[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
2)首先[7,0], [7,1]正确;对于[6,1]要求前面有一个比它高的,所以在idx=1插入[6,1];对于[5,0],要求前面有没有比它高的,所以在idx=0插入[5,0]…

解法

class Solution(object):
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """
        res = []
        people = sorted(people, key = lambda(h, k):(-h, k))
        for p in people:
            res.insert(p[1], p)
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值