Number of Airplanes in the Sky(数飞机)

问题

Given an interval list which are flying and landing time of the flight. How many airplanes are on the sky at most?

Notice

If landing and flying happens at the same time, we consider landing should happen at first.

Have you met this question in a real interview? Yes
Example
For interval list

[
[1,10],
[2,3],
[5,8],
[4,7]
]
Return 3

分析

我们构造一个数据结构,有左右边界。然后我们对其排序后,只要是左边的重合部分就表示飞机在空中。到达一个右边界表示要移除一个,循环结束后得到的最大值就是要的结果。

代码

/**
 * Definition of Interval:
 * public classs Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this.start = start;
 *         this.end = end;
 *     }
 */


public class Solution {
    /*
     * @param airplanes: An interval array
     * @return: Count of airplanes are in the sky.
     */
    public int countOfAirplanes(List airplanes) {
        // write your code here
        List nodes = new ArrayList<>();
        for (Interval interval : airplanes) {
            nodes.add(new Node(interval.start, true));
            nodes.add(new Node(interval.end, false));
        }
        Collections.sort(nodes);
        int count = 0;
        int max = 0;
        for (Node node :
                nodes) {
            if (node.isStart) {
                count++;
                max = Math.max(count, max);
            } else {
                count--;
            }
        }
        return max;
    }

    private class Node implements Comparable {
        int index;
        boolean isStart;

        public Node(int index, boolean isStart) {
            this.index = index;
            this.isStart = isStart;
        }

        @Override
        public int compareTo(Node o) {
            if (index > o.index) {
                return 1;
            } else if (index < o.index) {
                return -1;
            } else {
                if (isStart) {
                    return 1;
                } else {
                    return -1;
                }
            }
        }
    }
}

你可能感兴趣的:(Number of Airplanes in the Sky(数飞机))