Created
April 2, 2018 06:39
-
-
Save jianminchen/adcd6e7b004171ada90d6f7bf975767d to your computer and use it in GitHub Desktop.
Give mock interview to the peer - Leetcode 56 - Merge intervals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Given a collection of intervals, merge all overlapping intervals. | |
For example, | |
Given [1,3],[2,6],[8,10],[15,18], | |
return [1,6],[8,10],[15,18]. | |
// Approach: | |
// - Maintain an interval array, initially an empty array | |
// - Try to insert an interval1 into the array, | |
// We should insert, if and only if there is no overlapping interval in the array with interval1 | |
// input: [1,3],[2,6],[8,10],[15,18] | |
// 1. ans = [] | |
// -> Try to insert [1, 3] | |
// -> directly append because of an empty array, | |
// Now: ans = [[1, 3]] | |
// 2. ans = [[1, 3]], try to insert [2, 6] -> interval | |
// Loop through ans, let's say we are iterating i from 0 to ans.length | |
// ans[i], there is a overlap if, | |
// ans[i][0] <= interval[0] <= ans[i][1] OR | |
// ans[i][0] <= interval[1] <= ans[i][1] | |
// ans[i][0] = Math.min(ans[i][0], interval[0]) | |
// ans[i][1] = Math.max(ans[i][1], interval[1]) | |
// Time Complexity: O(N^2) | |
// Space Complexity: O(N) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment