spareTime

类似merge interval,唯一的区别是输出,输出空闲的时间段,merge完后,再把两两个之间的空的输出就好,注意要加上0 - 第一个的start time

public class spareTime {

    public List<int[]> spareTimeCal(int[][] meetings)
    {
        List<int[]> res = new ArrayList<>();
        int[][] mergedMeetings = mergeMeetings(meetings);
        int start = 0;
        for(int i = 0; i< mergedMeetings.length; i++)
        {
            res.add(new int[]{start, mergedMeetings[i][0]});
            start = mergedMeetings[i][1];
        }
        return res;
    }

    public int[][] mergeMeetings(int[][] meetings)
    {
        Arrays.sort(meetings , (int[] a, int[] b) -> {
            if(a[0] == b[0])
            {
                return b[1]- a[1];
            }
            return a[0]-b[0];
        });

        LinkedList<int[]> res = new LinkedList<>();
        res.addLast(meetings[0]);

        for(int i = 0; i< meetings.length; i++)
        {
            int[] next = meetings[i];
            int[] current = res.getLast();
            if(current[0] <= next[0] && next[1] <= current[1])
            {
                continue;
            }
            else if(next[0] <= current[1] && current[1] < next[1])
            {
                res.removeLast();
                res.addLast(new int[]{current[0], next[1]});
            }
            else if(current[1] < next[0])
            {
                res.add(next);
            }
        }
        return res.toArray(new int[0][0]);
    }
     
}

Last updated