xinyu04

导航

[Google] LeetCode 2158 Amount of New Area Painted Each Day 思维+set

There is a long and thin painting that can be represented by a number line. You are given a 0-indexed 2D integer array paint of length n, where paint[i] = [starti, endi]. This means that on the ith day you need to paint the area between \(start_i\) and \(end_i\).

Painting the same area multiple times will create an uneven painting so you only want to paint each area of the painting at most once.

Return an integer array worklog of length \(n\), where worklog[i] is the amount of new area that you painted on the \(i\)th day.

Solution

每次只能涂抹一定区间的颜色,当有重复的部分时,只能涂抹剩下不重复的区间。我们先用 \(set\) 将所有的点 \(insert\), 当遍历到某一个区间时, 我们用 \(set.lower\_bound\) 来找到符合条件的 start point,然后将这段区间在 \(set\) 里面删除:

点击查看代码
class Solution {
private:
    set<int> seg;
    vector<int> ans;
    int Min = 50004, Max = -1;
public:
    vector<int> amountPainted(vector<vector<int>>& paint) {
        int n = paint.size();
        for(int i=0;i<n;i++){
            Min = min(Min, paint[i][0]); Max = max(Max, paint[i][1]);
        }
        for(int i=Min;i<=Max;i++)seg.insert(i);
        int cnt;
        
        for(int i=0;i<n;i++){
            cnt = 0;
            // find the lower bound of start point
            auto it = seg.lower_bound(paint[i][0]);
            while(it!=seg.end() && *it<paint[i][1]){
                cnt++; it = seg.erase(it);
            }
            ans.push_back(cnt);
        }
        return ans;
    }
};

posted on 2022-07-20 21:19  Blackzxy  阅读(330)  评论(0编辑  收藏  举报