leetcode452. Minimum Number of Arrows to Burst Balloons

  • 2019 年 11 月 12 日
  • 筆記

題目要求

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 104balloons.

An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstartand xendbursts 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).

現在給一個二維數組,二維數組的每一行代表著氣球在x軸上的起始坐標和結束坐標。現在會以儲值X軸的方向開槍,問最少開多少槍可以將所有的氣球打落。

思路和程式碼

假設現在有一個氣球位於xi-xj,假如在xj之前一槍不開,則該氣球一定無法被擊落。因此如果將所有氣球的xj位置按照從小到大排序,並且從第一個氣球的xj處開一槍,則可以知道該位置最多可以擊落多少個氣球。再從下一個氣球的xj位置處開第二槍,依次遞推。直到擊落最後一個氣球為止。

    public int findMinArrowShots(int[][] points) {          if (points == null || points.length==0) {return 0;}          Arrays.sort(points, Comparator.comparingInt(o -> o[1]));          int count = 0;          int index = 0;          while (index < points.length) {              int right = points[index][1];              while (++index < points.length && points[index][0] <= right);              count++;          }          return count;      }