Data structure basics day4

Topic: 240. Searching a two-dimensional matrix II

Solution: Z shape

Traverse from the upper right corner, query the size from the lower left to (x, y), if it is greater than target, then y–, if less than target, x++

class Solution {
    
    
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
    
    
        int m=matrix.size(), n=matrix[0].size();
        int x=0, y=n-1;
        while(x<m && y>=0){
    
    
            if(matrix[x][y]==target){
    
    
                return true;
            }else if(matrix[x][y]>target){
    
    
                --y;
            }else{
    
    
                ++x;
            }
        }
        return false;
    }
};

Topic: 435. No overlapping intervals

Solution: Greedy

The right endpoints of each interval are sorted from small to large. The right endpoint of the first interval is initially used as the right boundary. It is judged whether the left endpoint of the next interval is greater than or equal to the right boundary. If so, the right boundary is updated to the right endpoint of the new interval. Otherwise, determine the next interval.

class Solution {
    
    
public:
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
    
    
        if(intervals.empty()) return 0;	//特判
        sort(intervals.begin(), intervals.end(), [](vector<int> &u, vector<int> &v){
    
    
            return u[1]<v[1];
        });	//按照右端点对intervals进行排序,注意判断函数的写法[]{}
        int n = intervals.size();
        int right = intervals[0][1], ans=1;	//初始化右界right和ans(不重叠区间数量,注意为1,即intervals[0])
        for(int i=1; i<n; ++i){
    
    	//从1开始
            if(intervals[i][0]>=right){
    
    	//如果区间左端点大于等于右界,则不重叠,ans++,更新右界
                ++ans;
                right = intervals[i][1];
            }
        }
        return n-ans;	//总数减去不重叠区间数即为需要去除的区间数量
    }
};

Guess you like

Origin blog.csdn.net/qq_43606119/article/details/130274987