Number of Airplanes in the Sky

Description

Given an list interval, which are taking off and landing time of the flight. How many airplanes are there at most at the same time in the sky?

If landing and taking off of different planes happen at the same time, we consider landing should happen at first.

Example

Example 1:

Input: [(1, 10), (2, 3), (5, 8), (4, 7)]
Output: 3
Explanation:
The first airplane takes off at 1 and lands at 10.
The second ariplane takes off at 2 and lands at 3.
The third ariplane takes off at 5 and lands at 8.
The forth ariplane takes off at 4 and lands at 7.
During 5 to 6, there are three airplanes in the sky.

Example 2:

Input: [(1, 2), (2, 3), (3, 4)]
Output: 1
Explanation: Landing happen before taking off.

思路:扫描线
/**
 * Definition of Interval:
 * public classs Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this.start = start;
 *         this.end = end;
 *     }
 * }
 */
class Event{
    int time;
    int flag;
     
    Event(int t, int s) {
        this.time = t;
        this.flag = s;
    }
}
public class Solution {
    /**
     * @param airplanes: An interval array
     * @return: Count of airplanes are in the sky.
     */
     public static Comparator<Event> comp = new Comparator<Event>() {
        public int compare(Event e1, Event e2) {
            if (e1.time == e2.time) {
                return e1.flag - e2.flag;
            }
            return e1.time - e2.time;
        }
    };
    public int countOfAirplanes(List<Interval> airplanes) {
         List<Event> list = new ArrayList<>();
        for (Interval i : airplanes) {
            list.add(new Event(i.start, 1));
            list.add(new Event(i.end, 0));
        }
         
        Collections.sort(list, comp);
        int count = 0, ans = 0;
        for (Event e: list) {
            if (e.flag == 1) {
                count++;
            } else {
                count --;
            }
            ans = Math.max(ans, count);
        }
        return ans;
    }
}

  

猜你喜欢

转载自www.cnblogs.com/FLAGyuri/p/12077337.html
sky