Monday, April 24, 2017

Number of Airplanes in the Sky

Sweep Line
因为在compare里面也涉及了landing优先于flying的问题,所以起初我把isStart设置为boolean就不是很好用,而设置为int更容易进行比较。
另外一个语法问题是对于ArrayList sort要用Collections.sort();

/**
 * Definition of Interval:
 * public classs Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this.start = start;
 *         this.end = end;
 *     }
 */
class Tuple {
    int time;
    int isStart;
    public Tuple(int time, int isStart) {
        this.time = time;
        this.isStart = isStart;
    }
}
class Solution {
    /**
     * @param intervals: An interval array
     * @return: Count of airplanes are in the sky.
     */
    public int countOfAirplanes(List<Interval> airplanes) {
        // write your code here
        if (airplanes == null || airplanes.size() == 0) return 0;
        int max = 0;
        List<Tuple> times = new ArrayList<>();
        for (Interval inter : airplanes) {
            times.add(new Tuple(inter.start, 1));
            times.add(new Tuple(inter.end, 0));
        }
        Collections.sort(times, new Comparator<Tuple>() {
            @Override
            public int compare(Tuple t1, Tuple t2) {
                if (t1.time == t2.time) {
                    return t1.isStart - t2.isStart;
                }
                return t1.time - t2.time;
            }
        });
        int curr = 0;
        for (Tuple t : times) {
            if (t.isStart == 1) {
                curr++;
                max = Math.max(max, curr);
            } else {
                curr--;
            }
        }
        return max;
    }
}

No comments:

Post a Comment