题目传送门
自定义sort题目
注意,本题中由于都是数字日志时保证原相对顺序,那么就要求有以下两种思路:
1、 使用稳定的排序算法,如归并排序或者插入排序这种。(一般不用冒泡,太慢了)。
2、我们自己封装一个类,保存string,和原id下标,直接调用sort函数就行,比较简单。
在实现思路1的过程中,就需要使用stable_sort函数,在使用lambda表达式写比较函数时,需要注意:
1、comp比较函数对象(即满足比较 (Compare) 概念的对象),若第一参数小于(即先序于)第二参数则返回 true
怎么理解呢,就是只有我们需要调整第一参数和第二参数的位置时,才返回true,具体来说第一参数在原数组中位置靠后,第二参数位置靠前,所以一旦确定了需要调整顺序,那么返回true,进行调整。
也可以这么理解:
[&] (const string x, const string y), x是后者,y是前者,return x
class Solution {
public:
vector reorderLogFiles(vector& logs) {
stable_sort(logs.begin(),logs.end(),[&](const string &a,const string &b)->bool{
//a日志靠后,b日志靠前
int i = 0,j = 0;
while(a[i] != ' ') i++;
while(b[j] != ' ') j++;
string stra = a.substr(i+1);
string strb = b.substr(j+1);
//只要a是数字日志,那么就不用调换
if(stra[0] >= '0' && stra[0]<='9') return false;
//a不是数字日志,b是数字日志,需要调换
if(strb[0] >= '0' && strb[0]<='9') return true;
//a,b都是字母日志,就按照普通我们熟悉的写法
if(stra.compare(strb) == 0){
return a.compare(b)<0;
}else
return stra.compare(strb)<0;
});
return logs;
}
};
加了一些字符串的标准操作方法
class Solution {
public:
vector reorderLogFiles(vector& logs) {
stable_sort(logs.begin(),logs.end(),[&](const string &a,const string &b)->bool{
//a日志靠后,b日志靠前
int i = a.find_first_of(' ');
int j = b.find_first_of(' ');
string stra = a.substr(i+1);
string strb = b.substr(j+1);
//只要a是数字日志,那么就不用调换
if(isdigit(a[i+1])) return false;
//a不是数字日志,b是数字日志,需要调换
if(isdigit(b[j+1])) return true;
//a,b都是字母日志,就按照普通我们熟悉的写法
if(stra.compare(strb) == 0){
return a.compare(b)<0;
}else
return stra.compare(strb)<0;
});
return logs;
}
};
作者:sheldon-29
链接:https://leetcode-cn.com/problems/reorder-data-in-log-files/solution/yan-jiu-yi-xia-sort-by-sheldon-29-0sr4/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。



