[Let's button brushing questions | Twenty-first day]

Table of contents

Foreword:

435. Non-overlapping intervals - LeetCode

763. Divide letter intervals - LeetCode

Summarize:


Foreword:

Today, it is still a question of the greedy algorithm type.

435. Non-overlapping intervals - LeetCode

Given a collection of intervals  intervals , where  intervals[i] = [starti, endi] . Returns  the minimum number of intervals that need to be removed such that the remaining intervals do not overlap

 In fact, this question has the same idea as the overlapping problem of bow and arrow shooting balloons that we have done before, but it is slightly different in processing data. When we determine the area, at least how many intervals should be removed, in fact, the minimum number of overlapping intervals is required.

class Solution {
public:
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        int n = intervals.size();
        if (n == 0) 
        return 0;
        sort(intervals.begin(), intervals.end(), [](const auto& a, const auto& b) {
            return a[0] < b[0];
        });

        int result=0;
        int end = intervals[0][1];

        for(int i=1;i<n;i++)
        {
            if(intervals[i][0]>=end)
            {
                  end = intervals[i][1]; 
            }
            else{
                 end = min(end, intervals[i][1]);
                result++;
            }
        

        }

        return result;
    }
};

763. Divide letter intervals - LeetCode

You are given a string s. We need to divide this string into as many fragments as possible, and the same letter appears in at most one fragment.

Note that the division results need to satisfy: connect all the division results in order, and the obtained string is still s.

Returns a list representing the length of each string fragment.

The idea of ​​this question is indeed a bit complicated:

Traverse the string to get the position of the first and last occurrence of each character to form a range. If the ranges intersect, they will be merged into a large range. If they do not intersect, the length of the range will be calculated and added to the result.

class Solution {
public:
    vector<int> partitionLabels(string S) {
       std::unordered_map<char, int> lastPosMap;
        for (int i = 0; i < S.size(); i++) { 
            lastPosMap[S[i]] = i;
        }
        std::vector<int> result;
        int start = 0;
        int end = 0;
        for (int i = 0; i < S.size(); i++) {
            end = std::max(end, lastPosMap[S[i]]);
            if (i == end) {
                result.push_back(end - start + 1);
                start = i + 1;
            }
        }
        return result;
    }
};
  

Summarize:

        Lay the foundation.

If my content is helpful to you, please like, comment and bookmark . Creation is not easy, everyone's support is my motivation to persevere!

 



 

Guess you like

Origin blog.csdn.net/fckbb/article/details/131819562