接上文,本篇文章我们来讲
解决方案
自定义排序
思路
根据题意自定义排序的比较方式。比较时,先将数组日志按照第一个空格分成两部分字符串,其中第一部分为标识符。第二部分的首字符可以用来判断该日志的类型。
两条日志进行比较时,需要先确定待比较的日志的类型,然后按照以下规则进行比较:
字母日志始终小于数字日志。
数字日志保留原来的相对顺序。当使用稳定的排序算法时,可以认为所有数字日志大小一样。当使用不稳定的排序算法时,可以用日志在原数组中的下标进行比较。
字母日志进行相互比较时,先比较第二部分的大小;如果相等,则比较标识符大小。比较时都使用字符串的比较方式进行比较。
定义比较函数 logCompare 时,有两个输入 log1 和 log2。
当相等时,返回 0;当 log1 大时,返回正数;当 log2 大时,返回负数。

代码
Python3
class Solution: def reorderLogFiles(self, logs: List[str]) -> List[str]: def trans(log: str) -> tuple: a, b = log.split(' ', 1) return (0, b, a) if b[0].isalpha() else (1,) logs.sort(key=trans) # sort 是https://zhida.zhihu.com/search?content_id=236126939&content_type=Article&match_order=1&q=%E7%A8%B3%E5%AE%9A%E6%8E%92%E5%BA%8F&zhida_source=entity return logs
C++
class Solution {
public:
vector<string> reorderLogFiles(vector<string>& logs) {
stable_sort(logs.begin(), logs.end(), [&](const string & log1, const string & log2) {
int pos1 = log1.find_first_of(" ");
int pos2 = log2.find_first_of(" ");
bool isDigit1 = isdigit(log1[pos1 + 1]);
bool isDigit2 = isdigit(log2[pos2 + 1]);
if (isDigit1 && isDigit2) {
return false;
}
if (!isDigit1 && !isDigit2) {
string s1 = log1.substr(pos1);
string s2 = log2.substr(pos2);
if (s1 != s2) {
return s1 < s2;
}
return log1 < log2;
}
return isDigit1 ? false : true;
});
return logs;
}
};