扫描线

224 阅读1分钟

Lintcode 391空中飞机最多个数

思路:只在起飞降落时改变个数,起飞+1,降落-1。把start和end放进两个数组中并排序,先算降落再算起飞。计算完start即可,因为end之后减少个数。

 * 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.
     */
    static class Point {
        public int T;
        public int S;
        public Point() {
        }
        public Point(int T, int S) {
            this.T = T;
            this.S = S;
        }
    }

    public int countOfAirplanes(List<Interval> airplanes) {
        // write your code here
        List<Point> list = new ArrayList<>(airplanes.size()*2);
        for(Interval i : airplanes){
            list.add(new Point(i.start,1));
            list.add(new Point(i.end,0));
        }

        Collections.sort(list,(Point p1,Point p2)->{
            if(p1.T == p2.T) return p1.S-p2.S;
            return p1.T-p2.T;
        });

        int cnt=0;
        int ans=0;
        for(Point p:list){
            if(p.S==1) cnt++;
            else cnt--;
            ans = Math.max(ans,cnt);
        }
        return ans;
    }
}

920 Meeting Rooms

思路:比较end time 和 start time。