C++对二维vector或数组,按照某一维度排序,Leetcode中的写法

方法

// C++ code to demonstrate sorting of a 
// 2D vector on basis of a column 
#include<iostream> 
#include<vector> // for 2D vector 
#include<algorithm> // for sort() 
using namespace std; 
  
// Driver function to sort the 2D vector 
// on basis of a particular column 
bool sortcol( const vector<int>& v1, 
               const vector<int>& v2 ) { 
 return v1[1] < v2[1]; 
} 
  
int main() 
{ 
    // Initializing 2D vector "vect" with 
    // values 
    vector< vector<int> > vect{{3, 5, 1}, 
                                {4, 8, 6}, 
                                {7, 2, 9}}; 
  
    // Number of rows; 
    int m = vect.size(); 
  
    // Number of columns (Assuming all rows 
    // are of same size).  We can have different 
    // sizes though (like Java). 
    int n = vect[0].size(); 
      
    // Displaying the 2D vector before sorting 
    cout << "The Matrix before sorting is:\n"; 
    for (int i=0; i<m; i++) 
    { 
        for (int j=0; j<n ;j++) 
            cout << vect[i][j] << " "; 
        cout << endl; 
    }                                
  
    // Use of "sort()" for sorting on basis 
    // of 2nd column 
    sort(vect.begin(), vect.end(),sortcol); 
  
    // Displaying the 2D vector after sorting 
    cout << "The Matrix after sorting is:\n"; 
    for (int i=0; i<m; i++) 
    { 
        for (int j=0; j<n ;j++) 
            cout << vect[i][j] << " "; 
        cout << endl; 
    } 
    return 0; 
} 
  • 输出
The Matrix before sorting is:
3 5 1
4 8 6
7 2 9
The Matrix after sorting is:
7 2 9
3 5 1
4 8 6

leetcode中的情况

  • compare函数前要加static
class Solution {
public:
    static bool compare( const vector<int>& v1, const vector<int>& v2){
        return v1[1]<v2[1];
    }
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        if(intervals.size()==0) return 0;
        sort(intervals.begin(), intervals.end(), compare);
        int count=1; //至少有一个是满足要求的
        int end_time=intervals[0][1];
        for(auto event: intervals){
            if(event[0]>=end_time){
                count++;
                end_time=event[1];
            }
        }
        return intervals.size()-count;
    }
};

参考geeksforgeeks

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值