452. Minimum Number of Arrows to Burst Balloons

这篇具有很好参考价值的文章主要介绍了452. Minimum Number of Arrows to Burst Balloons。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.

Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.

Given the array points, return the minimum number of arrows that must be shot to burst all balloons.

Example 1:

Input: points = [[10,16],[2,8],[1,6],[7,12]]
Output: 2
Explanation: The balloons can be burst by 2 arrows:

  • Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].
  • Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].
    Example 2:

Input: points = [[1,2],[3,4],[5,6],[7,8]]
Output: 4
Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.
Example 3:

Input: points = [[1,2],[2,3],[3,4],[4,5]]
Output: 2
Explanation: The balloons can be burst by 2 arrows:

  • Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].
  • Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].

Constraints:

1 <= points.length <= 105
points[i].length == 2
-231 <= xstart < xend <= 231 - 1

Approach

452. Minimum Number of Arrows to Burst Balloons,程序员英语面试,算法,leetcode
First, let’s consider the following example:
Input: points = [[10,12],[2,8],[1,6],[7,12]].
It is clear that the balloons can be burst by 2 arrows. The first arrow can be shot within the range of 2 to 6.
For instance, shooting an arrow at x = 6 will burst the balloons [2,8] and [1,6].
The last arrow can be shot within the range of 10 to 12.
For example, shooting an arrow at x = 11 will burst the balloons [10,16] and [7,12].

However, it can be challenging to write the code by given array in a specific order.
To write code efficiently, sort the points by their start index (the first index of the coordinates).

For instance, the initial balloon is located at [1,6].
To burst this balloon, the arrow must be shot within a range of 1 to 6. Then, we encounter another balloon. Since we have sorted the points beforehand, we can determine if the balloons overlap by comparing the second balloon’s start and the first balloon’s end (6 > 2).
To burst two overlapping balloons with coordinates [1,6] and [2,8], only one arrow is needed with a range of [2,6]. However, the third balloon cannot be reached by the first arrow, which has a range of [2,6], so another arrow is required. Following the same analysis as before, a second arrow with a range of [10,12] can burst the balloons [10,16] and [7,12].

Now, let’s to write the code.
To facilitate identifying overlaps in a single traversal, we sort in ascending order on the xstart.

sort(points.begin() , points.end() ,compare );

Then we declare an int variable arrowEnd to represent the end of the right range of the current arrow.
Because we have to shoot down each balloon and these are in ascending order, the shooting range of the first arrow is the position of the first balloon. So we assign points[0][1] to arrowEnd.

We initialise the int variable minNum with one,which means the minimum number of arrows. Then we use a for loop to iterate over each balloon.

 for(int i=0;i<points.size();i++)
  {
      ...
   }

for each balloon, we check whether the range of the current arrow overlaps with the current balloon, which means this arrow can shoot the current balloon. if the end of the range of the arrow is greater than the beginning of the range of the balloon, they must be overlapping intervals.

we sorted balloons in ascending order on the xstart before, and we consider arrow by check balloon from left to right, So we don’t need consider begin of arrow’s shooting range.
452. Minimum Number of Arrows to Burst Balloons,程序员英语面试,算法,leetcode
we can see this picture. if current balloon’s xend is larger than arrowEnd,like balloon 1, the arrow can be shot within its range. But if current balloon’s xend is smaller than arrowEnd,like balloon 2, the arrow can’t be shot at any position within its range. we should modify the arrow range by assign smaller one between arrowEnd and the point’s end.

if(arrowEnd>=points[i][0] )
 {
     arrowEnd = min(points[i][1] , arrowEnd);
 }

if end of the arrow’s range is smaller than begin of the balloon’s range, there is no overlopping.
452. Minimum Number of Arrows to Burst Balloons,程序员英语面试,算法,leetcode
we need another arrow to shoot the current balloon. we add one to minNum, and change the range of the new arrow by assigning the end of the current balloon to arrowEnd.

else
{
    minNum++;
    arrowEnd=points[i][1];
}

after we iterate all balloons, we return minNum.

the Time complexity is O(NlogN).
the Space complexity is O(1).

code

bool compare(vector<int> &a, vector<int> &b);
class Solution {
public:
    int findMinArrowShots(vector<vector<int>>& points) {
        sort(points.begin() , points.end() ,compare );
        int arrowEnd = points[0][1];
        int minNum =1;

        for(int i=0;i<points.size();i++)
        {
            if(arrowEnd>=points[i][0] )
            {
                arrowEnd = min(points[i][1] , arrowEnd);
            }
            else
            {
                minNum++;
                arrowEnd=points[i][1];
            }
        }
        return minNum;
    }
};

bool compare(vector<int> &a, vector<int> &b)
{
    if(a[0] != b[0])
    {
        return a[0]<b[0];
    }
    return a[1]<b[1];
}

leetcode 452. Minimum Number of Arrows to Burst Balloons

https://www.youtube.com/watch?v=_WIFehFkkig

英语参考

Idea:
We know that eventually we have to shoot down every balloon, so for each ballon there must be an arrow whose position is between balloon[0] and balloon[1] inclusively. Given that, we can sort the array of balloons by their ending position. Then we make sure that while we take care of each balloon in order, we can shoot as many following balloons as possible.

So what position should we pick each time? We should shoot as to the right as possible, because since balloons are sorted, this gives you the best chance to take down more balloons. Therefore the position should always be balloon[i][1] for the ith balloon.

This is exactly what I do in the for loop: check how many balloons I can shoot down with one shot aiming at the ending position of the current balloon. Then I skip all these balloons and start again from the next one (or the leftmost remaining one) that needs another arrow.

Example:

balloons = [[7,10], [1,5], [3,6], [2,4], [1,4]]
After sorting, it becomes:

balloons = [[2,4], [1,4], [1,5], [3,6], [7,10]]
So first of all, we shoot at position 4, we go through the array and see that all first 4 balloons can be taken care of by this single shot. Then we need another shot for one last balloon. So the result should be 2.

Code:

public int findMinArrowShots(int[][] points) {
if (points.length == 0) {
return 0;
}
Arrays.sort(points, (a, b) -> a[1] - b[1]);
int arrowPos = points[0][1];
int arrowCnt = 1;
for (int i = 1; i < points.length; i++) {
if (arrowPos >= points[i][0]) {
continue;
}
arrowCnt++;
arrowPos = points[i][1];
}
return arrowCnt;
}

Here I provide a concise template that I summarize for the so-called “Overlapping Interval Problem”, e.g. Minimum Number of Arrows to Burst Balloons, and Non-overlapping Intervals etc. I found these problems share some similarities on their solutions.

Sort intervals/pairs in increasing order of the start position.
Scan the sorted intervals, and maintain an “active set” for overlapping intervals. At most times, we do not need to use an explicit set to store them. Instead, we just need to maintain several key parameters, e.g. the number of overlapping intervals (count), the minimum ending point among all overlapping intervals (minEnd).
If the interval that we are currently checking overlaps with the active set, which can be characterized by cur.start > minEnd, we need to renew those key parameters or change some states.
If the current interval does not overlap with the active set, we just drop current active set, record some parameters, and create a new active set that contains the current interval.
int count = 0; // Global parameters that are useful for results.
int minEnd = INT_MAX; // Key parameters characterizing the “active set” for overlapping intervals, e.g. the minimum ending point among all overlapping intervals.
sort(points.begin(), points.end()); // Sorting the intervals/pairs in ascending order of its starting point
for each interval {
if(interval.start > minEnd) { // If the
// changing some states, record some information, and start a new active set.
count++;
minEnd = p.second;
}
else {
// renew key parameters of the active set
minEnd = min(minEnd, p.second);
}
}
return the result recorded in or calculated from the global information;
For example, for the problem Minimum “Number of Arrows to Burst Balloons”, we have

Sort balloons in increasing order of the start position.
Scan the sorted pairs, and maintain a pointer for the minimum end position for current “active balloons”, whose diameters are overlapping.
When the next balloon starts after all active balloons, shoot an arrow to burst all active balloons, and start to record next active balloons.
int findMinArrowShots(vector<pair<int, int>>& points) {
int count = 0, minEnd = INT_MAX;
sort(points.begin(), points.end());
for(auto& p: points) {
if(p.first > minEnd) {count++; minEnd = p.second;}
else minEnd = min(minEnd, p.second);
}
return count + !points.empty();
}
For the problem “Non-overlapping Intervals”, we have

int eraseOverlapIntervals(vector& intervals) {
int total = 0, minEnd = INT_MIN, overNb = 1;
sort(intervals.begin(), intervals.end(), [&](Interval& inter1, Interval& inter2) {return inter1.start < inter2.start;});
for(auto& p: intervals) {
if(p.start >= minEnd) {
total += overNb-1;
overNb = 1;
minEnd = p.end;
}
else {
overNb++;
minEnd = min(minEnd, p.end);
}
}
return total + overNb-1;
}

To facilitate identifying coincidence in a single traversal, we sort in ascending order on the right文章来源地址https://www.toymoban.com/news/detail-815717.html

到了这里,关于452. Minimum Number of Arrows to Burst Balloons的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java异常 #Number of lines annotated by Git is not equal to number of lines in the file, check file …

    在项目中某个 java 文件左边栏右键查看代码版本履历(Annotate)时无法显示,IDEA 提示:Number of lines annotated by Git is not equal to number of lines in the file, check file encoding and line separators.   这个问题涉及到不同操作系统下文本文件的换行符差异引起的。在不同操作系统中,文本文件的

    2024年02月03日
    浏览(43)
  • Leetcode 3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K

    Leetcode 3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K 1. 解题思路 2. 代码实现 题目链接:3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K 这一题我的思路上就是一个二分的思路,先确定一个上下界,然后不断通过二分来找到最大的price不超过k的值。 因此,剩下的

    2024年01月20日
    浏览(49)
  • 1249. Minimum Remove to Make Valid Parentheses

    Given a string s of  \\\'(\\\'  ,  \\\')\\\'  and lowercase English characters. Your task is to remove the minimum number of parentheses (  \\\'(\\\'  or  \\\')\\\' , in any positions ) so that the resulting  parentheses string  is valid and return  any  valid string. Formally, a  parentheses string  is valid if and only if: It is the empty string, contains only lowe

    2024年02月05日
    浏览(35)
  • unity异常:InvalidOperationException: Burst failed to compile the function pointer `Int32

    异常信息具体如下: InvalidOperationException: Burst failed to compile the function pointer `Int32 ValidateCollinear$BurstManaged(Unity.Mathematics.float2*, Int32, Single)` Unity.Burst.BurstCompiler.Compile (System.Object delegateObj, System.Reflection.MethodInfo methodInfo, System.Boolean isFunctionPointer, System.Boolean isILPostProcessing) (at Lib

    2024年02月06日
    浏览(44)
  • LeetCode447. Number of Boomerangs

    You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Return the number of boomerangs. Example 1: Input: points = [[0,0],[1,0],[2,0]] Output: 2 Explanation: The two boomerangs

    2024年02月02日
    浏览(36)
  • LeetCode 933. Number of Recent Calls

    ou have a  RecentCounter  class which counts the number of recent requests within a certain time frame. Implement the  RecentCounter  class: RecentCounter()  Initializes the counter with zero recent requests. int ping(int t)  Adds a new request at time  t , where  t  represents some time in milliseconds, and returns the number of requests that has h

    2024年02月08日
    浏览(47)
  • LeetCode每日一题(2457. Minimum Addition to Make Integer Beautiful)

    You are given two positive integers n and target. An integer is considered beautiful if the sum of its digits is less than or equal to target. Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful. Example 1: Input: n = 16, target = 6 Output: 4 Explanation: Init

    2023年04月16日
    浏览(98)
  • LeetCode //C - 933. Number of Recent Calls

    You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: RecentCounter() Initializes the counter with zero recent requests. int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the pas

    2024年01月23日
    浏览(49)
  • 【算法】Number of Closed Islands 统计封闭岛屿的数目

    二维矩阵 grid 由 0 (土地)和 1 (水)组成。岛是由最大的4个方向连通的 0 组成的群,封闭岛是一个 完全 由1包围(左、上、右、下)的岛。 请返回 封闭岛屿 的数目。 行,列范围[1,100] , g r i d [ i ] [ j ] grid[i][j] g r i d [ i ] [ j ] ==0OR1 问题要求封闭island的数量,就是找出完全

    2024年02月10日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包