【Java】用最少數量的箭引爆氣球

package greedy;

import java.util.Arrays;
import java.util.Comparator;

public class findMinArrowShots {

    public static void main(String[] args){
        int[][] p = {{10,16}, {2,8}, {1,6}, {7,12}};
        System.out.println(findMinArrowShots.findMinArrowShots(p));
    }

    public static int findMinArrowShots(int[][] points){
        if (points.length == 0) {
            return 0;
        }
        // 按座標尾排序
        Arrays.sort(points, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                // 當返回值大於0交換,此次爲升序
                return o1[1] - o2[1];
            }
        });
//        System.out.println(Arrays.deepToString(points));
        // 箭
        int arrows = 1;

        int xStart,xEnd;
        // 第一個氣球尾
        int firstEnd = points[0][1];
        for (int[] p : points) {
            xStart = p[0];
            xEnd = p[1];
            // if the current balloon starts after the end of another one,
            // one needs one more arrow
            if (firstEnd < xStart) {
                arrows++;
                firstEnd = xEnd;
            }
        }
        return arrows;
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章