只有當 c <= a 且 b <= d 時,我們才認為區間 [a,b) 被區間 [c,d) 覆蓋。
示例:輸入:intervals = [[1,4],[3,6],[2,8]] 輸出:2
提示:1 <= intervals.length <= 1000
0 <= intervals[i][0] < intervals[i][1] <= 10^5
對於所有的 i != j:intervals[i] != intervals[j]
解題思路分析1、排序遍歷;時間複雜度O(nlog(n)),空間複雜度O(1)
func removeCoveredIntervals(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { if intervals[i][0] == intervals[j][0] { return intervals[i][1] > intervals[j][1] } return intervals[i][0] < intervals[j][0] }) res := 0 maxValue := intervals[0][1] for i := 1; i < len(intervals); i++ { if intervals[i][0] == intervals[i-1][0] { // 合併 res++ continue } if intervals[i][1] > maxValue { maxValue = intervals[i][1] // 更新 } else { res++ // 合併 } } return len(intervals) - res}
2、排序遍歷;時間複雜度O(nlog(n)),空間複雜度O(1)
func removeCoveredIntervals(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { if intervals[i][0] == intervals[j][0] { return intervals[i][1] > intervals[j][1] } return intervals[i][0] < intervals[j][0] }) res := 0 left := intervals[0][0] right := intervals[0][1] for i := 1; i < len(intervals); i++ { l, r := intervals[i][0], intervals[i][1] if left <= l && r <= right { // 合併 res++ } if right < r { // 更新 left = l right = r } } return len(intervals) - res}
3、排序遍歷;時間複雜度O(nlog(n)),空間複雜度O(1)
func removeCoveredIntervals(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { if intervals[i][0] == intervals[j][0] { return intervals[i][1] > intervals[j][1] } return intervals[i][0] < intervals[j][0] }) res := 0 maxValue := 0 for i := 0; i < len(intervals); i++ { if maxValue < intervals[i][1] { res++ maxValue = intervals[i][1] } } return res}
4、暴力法;時間複雜度O(n^2),空間複雜度O(1)
func removeCoveredIntervals(intervals [][]int) int { res := len(intervals) for i := 0; i < len(intervals); i++ { for j := 0; j < len(intervals); j++ { if i != j && intervals[j][0] <= intervals[i][0] && intervals[i][1] <= intervals[j][1] { res-- break } } } return res}
總結
Medium題目,區間系列問題,簡單思路直接暴力法,常規操作先排序再合併
最新評論