zoukankan      html  css  js  c++  java
  • LeetCode 452. Minimum Number of Arrows to Burst Balloons

    452. Minimum Number of Arrows to Burst Balloons

    Description Submission Solutions Add to List

    • Total Accepted: 7279
    • Total Submissions: 17030
    • Difficulty: Medium
    • Contributors: abhijeeg

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.

    An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.

    Example:

    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).

    Subscribe to see which companies asked this question.

    【题目分析】

    这是一道贪心算法的题目,实际上是给出了一系列的区间,求出最少可以把这些区间分为几组,使得每一组区间都有一个公共的交点。

    【思路】

    用贪心算法的思路去解决的话,如果我们已经选定了一个区间,那么只要找到其他的与这个区间相交的区间则可以把他们分为一组。首先我们把所有区间按照end point排序,然后从最小的开始选择,直到所有区间都被分组。返回此时的组数即可。

    【java代码】

     1 public class Solution {
     2     public int findMinArrowShots(int[][] points) {
     3         if(points == null || points.length == 0) return 0;
     4         Arrays.sort(points, new Comparator<int[]>() {
     5             public int compare(int[] a, int[] b) {
     6                 return (a[1] - b[1]);
     7             }
     8         });
     9         
    10         int curend = points[0][1];
    11         int count = 1;
    12         for(int[] p : points) {
    13             if(p[0] > curend) {
    14                 count++;
    15                 curend = p[1];
    16             }
    17             else continue;
    18         }
    19         
    20         return count;
    21     }
    22 }
  • 相关阅读:
    linux tcp中time_wait
    linux查看系统信息
    运行程序出错无法找到库文件
    安装keepalived
    python 深拷贝与浅拷贝
    python import eventlet包时提示ImportError: cannot import name eventlet
    [原创] 用两个queue实现stack的功能
    [原创] 用两个stack实现queue的功能
    [原创] 编写函数,实现对链表元素的排序与分类
    python 装饰器
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6403217.html
Copyright © 2011-2022 走看看