Intuition
To get meeting count, we just need to get dis-joint continous segments where meeting days are contained.
First sort this array, with order:
1.a[0] == b[0], compare a[1] > b[1]
2.a[0] < b[0], return -1;
3.a[0] > b[1], return 1;
Then travel in the sorted 2D array:
- meeting[i+1][0] > meeting[i][1]: means the new segment started, add a segment to result.
- meeting[i+1][0] <= meeting[i][1]:
2.1 if meeting[i+1][1] > meeting[i][1]: merge the prev segment’s end to meeting[i+1][1], in other words, enlarge the prev segment.
2.2 if meeting[i+1][1] > meeting[i][1]: means the prev segment contains the current segment, do nothing. - meeting[i+1][0] == meeting[i][1]: means the prev segment is adjacent to current segment, just check whether meeting[i+1][1] > meeting[i][1], if so, merge the prev segment’s end to meeting[i+1][1].
Total Time complexity is sorting cost: O(n*logn)
Approach
Complexity
- Time complexity:
- O(nlogn)
- Space complexity:
- O(n): The worst case is every segment length is 1 and all elements are in segments.
Code
// Runtime 61 ms Beats 100.00% of users with Java
// Memory 99.61 MB Beats 100.00% of users with Java
// Sort And get all dis-joint continous segment.
// T:O(nlogn), S:(n)
//
class Solution {
public int countDays(int days, int[][] meetings) {
Arrays.sort(meetings, (a, b) ->