minimum-number-of-arrows-to-burst-balloons(还挺好)

https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/

与会议室排期问题,很相似。

package com.company;

import java.util.*;

class Balloon {
    int[] points;
    boolean check;
    Balloon(int s, int e) {
        points = new int[2];
        points[0] = s;
        points[1] = e;
        check = false;
    }
}

class MyComparator implements Comparator<Balloon> {

    int index;
    MyComparator(int i) {
        index = i;
    }

    @Override
    public int compare(Balloon o1, Balloon o2) {
        return o1.points[index] - o2.points[index];
    }
}

class Solution {
    public int findMinArrowShots(int[][] points) {
        List<Balloon> endList = new ArrayList<>();
        List<Balloon> startList = new ArrayList<>();

        for (int i=0; i<points.length; i++) {
            Balloon balloon = new Balloon(points[i][0], points[i][1]);
            endList.add(balloon);
            startList.add(balloon);
        }
        Collections.sort(endList, new MyComparator(1));
        Collections.sort(startList, new MyComparator(0));

        int index = 0;
        int ret = 0;
        Iterator<Balloon> iter = endList.iterator();
        while (iter.hasNext()) {
            Balloon tmp = iter.next();
            if (tmp.check) {
                continue;
            }
            ret++;
            while (index < points.length && startList.get(index).points[0] <= tmp.points[1]) {
                startList.get(index).check = true;
                index++;
            }
        }
        return ret;
    }
}

public class Main {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Hello!");
        Solution solution = new Solution();

        // Your Codec object will be instantiated and called as such:
        int[][] points = {{10,16}, {2,8}, {1,6}, {7,12}};
        int ret = solution.findMinArrowShots(points);
        System.out.printf("ret:%d\n", ret);

        System.out.println();

    }

}

 

posted @ 2016-11-07 17:44  blcblc  阅读(369)  评论(0编辑  收藏  举报