返回介绍

solution / 1200-1299 / 1288.Remove Covered Intervals / README_EN

发布于 2024-06-17 01:03:21 字数 3404 浏览 0 评论 0 收藏 0

1288. Remove Covered Intervals

中文文档

Description

Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.

The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.

Return _the number of remaining intervals_.

 

Example 1:

Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.

Example 2:

Input: intervals = [[1,4],[2,3]]
Output: 1

 

Constraints:

  • 1 <= intervals.length <= 1000
  • intervals[i].length == 2
  • 0 <= li < ri <= 105
  • All the given intervals are unique.

Solutions

Solution 1

class Solution:
  def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
    intervals.sort(key=lambda x: (x[0], -x[1]))
    cnt, pre = 1, intervals[0]
    for e in intervals[1:]:
      if pre[1] < e[1]:
        cnt += 1
        pre = e
    return cnt
class Solution {
  public int removeCoveredIntervals(int[][] intervals) {
    Arrays.sort(intervals, (a, b) -> a[0] - b[0] == 0 ? b[1] - a[1] : a[0] - b[0]);
    int[] pre = intervals[0];
    int cnt = 1;
    for (int i = 1; i < intervals.length; ++i) {
      if (pre[1] < intervals[i][1]) {
        ++cnt;
        pre = intervals[i];
      }
    }
    return cnt;
  }
}
class Solution {
public:
  int removeCoveredIntervals(vector<vector<int>>& intervals) {
    sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) { return a[0] == b[0] ? b[1] < a[1] : a[0] < b[0]; });
    int cnt = 1;
    vector<int> pre = intervals[0];
    for (int i = 1; i < intervals.size(); ++i) {
      if (pre[1] < intervals[i][1]) {
        ++cnt;
        pre = intervals[i];
      }
    }
    return cnt;
  }
};
func removeCoveredIntervals(intervals [][]int) int {
  sort.Slice(intervals, func(i, j int) bool {
    if intervals[i][0] == intervals[j][0] {
      return intervals[j][1] < intervals[i][1]
    }
    return intervals[i][0] < intervals[j][0]
  })
  cnt := 1
  pre := intervals[0]
  for i := 1; i < len(intervals); i++ {
    if pre[1] < intervals[i][1] {
      cnt++
      pre = intervals[i]
    }
  }
  return cnt
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文