经典算法实战:重新排列日志文件(二)

接上文,本篇文章我们来讲

解决方案

自定义排序

思路

根据题意自定义排序的比较方式。比较时,先将数组日志按照第一个空格分成两部分字符串,其中第一部分为标识符。第二部分的首字符可以用来判断该日志的类型。

两条日志进行比较时,需要先确定待比较的日志的类型,然后按照以下规则进行比较:

字母日志始终小于数字日志。

数字日志保留原来的相对顺序。当使用稳定的排序算法时,可以认为所有数字日志大小一样。当使用不稳定的排序算法时,可以用日志在原数组中的下标进行比较。

字母日志进行相互比较时,先比较第二部分的大小;如果相等,则比较标识符大小。比较时都使用字符串的比较方式进行比较。

定义比较函数 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;
    }
};
相关推荐
keep intensify7 小时前
最长有效括号
算法·leetcode·动态规划
CoderYanger7 小时前
A.每日一题:1979. 找出数组的最大公约数
java·程序人生·算法·leetcode·面试·职场和发展·学习方法
猫头虎7 小时前
什么是ZCode for GLM-5.2?
开发语言·人工智能·python·科技·算法·ai编程·ai写作
长不胖的路人甲8 小时前
什么是赫夫曼树(哈夫曼树 / Huffman Tree)
python·算法·霍夫曼树
Warren2Lynch8 小时前
掌握 UML 构造型、标记定义与标记值:面向领域特定建模的 UML 扩展全面指南
大数据·算法·uml
157092511349 小时前
【无标题】
开发语言·python·算法
稚南城才子,乌衣巷风流9 小时前
换根法(Rerooting)算法详解
算法
晓子文集9 小时前
Tushare接口文档:期货交易日历(fut_trade_cal)
大数据·算法
^yi10 小时前
【Linux系统编程】进程状态的理解
算法·僵尸进程·孤儿进程·进程状态·挂起状态·阻塞状态
hhzz11 小时前
机器学习-算法模型系列文章:04-KNN 不做标准化就跑KNN?你的模型正在被一个特征“独裁“
人工智能·算法·机器学习