LeetCode. 3111. 覆盖所有点的最少矩形数目

101 阅读1分钟

题目

leetcode.cn/problems/mi… 给你一个二维整数数组 point ,其中 points[i] = [xi, yi] 表示二维平面内的一个点。同时给你一个整数 w 。你需要用矩形 覆盖所有 点。

每个矩形的左下角在某个点 (x1, 0) 处,且右上角在某个点 (x2, y2) 处,其中 x1 <= x2 且 y2 >= 0 ,同时对于每个矩形都 必须 满足 x2 - x1 <= w 。

如果一个点在矩形内或者在边上,我们说这个点被矩形覆盖了。

请你在确保每个点都 至少 被一个矩形覆盖的前提下,最少 需要多少个矩形。

注意: 一个点可以被多个矩形覆盖。

思路

忽略 y , 只关注 x. 将所有的 x 去重排序后,记录首个 x 为 start , 计算每个 x 与start 的差值,如果 > w 就多一个矩形,并且更新 start

代码

class Solution {
    public int minRectanglesToCoverPoints(int[][] points, int w) {

        List<Integer> list = new ArrayList<>();
        for (int[] point : points) {
            int x = point[0];
            list.add(x);
        }
        List<Integer> sortedList = list.stream().distinct().sorted().toList();
        int ans = 1;
        int start = sortedList.get(0);
        int index = 1;
        while (index < sortedList.size()) {
            if (sortedList.get(index) - start > w) {
                start = sortedList.get(index);
                ans++;
            }
            index++;
        }
        return ans;
    }
}

题解

leetcode.cn/problems/mi…