759 Employee free time

https://leetcode.com/problems/employee-free-time/

莟 218 å…ļ厞åŒēåˆĢ不大īŧŒ į”šč‡ŗæ›´įŽ€å•

/*
// Definition for an Interval.
class Interval {
    public int start;
    public int end;

    public Interval() {}

    public Interval(int _start, int _end) {
        start = _start;
        end = _end;
    }
};
*/

class Solution {
    class Node {
        public int time;
        public boolean start;
        public Node(int time, boolean start) {
            this.time = time;
            this.start = start;
        }
    }
    public List<Interval> employeeFreeTime(List<List<Interval>> schedule) {
        int numEmployee = schedule.size();
        List<Node> nodes = new ArrayList<>();
        for (int i = 0; i < numEmployee; i++) {
            List<Interval> sche = schedule.get(i);
            for (Interval inter : sche) {
                nodes.add(new Node(inter.start, true));
                nodes.add(new Node(inter.end, false));
            }
        }
        Collections.sort(nodes, (Node n1, Node n2) -> {
            if (n1.time != n2.time) {
                return n1.time - n2.time;
            }
            if (n1.start && !n2.start) {
                return -1;
            }
            if (!n1.start && n2.start) {
                return 1;
            }
            return 0;
        });
        
        int cnt = numEmployee;
        int start = -1;
        int end = 0;
        List<Interval> ans = new ArrayList<>();
        for (Node n : nodes) {
            if (n.start) {
                if (cnt == numEmployee && start != -1) {
                    end = n.time;
                    ans.add(new Interval(start, end));
                }
                cnt--;
            } else {
                cnt++;
                if (cnt == numEmployee) {
                    start = n.time;
                }
            }
        }
        return ans;
    }
}

Last updated