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

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

解决方案

自定义排序

思路

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

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

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

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

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

定义比较函数 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;
    }
};
相关推荐
OPEN-F6 分钟前
ROS2系列教程:上位机建图与导航(原理综合)
算法·机器人
weixin_307779137 分钟前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
tomwang032223 分钟前
路径优化建模、优化算法分类及工程化小结
算法·数学建模·分类
小羊没烦恼!25 分钟前
Ajax与JSON的一些总结
android·java·前端·数据库·mysql·算法·okhttp
by2099931 分钟前
哈希表——快速找到数据:冲突、删除与扩容的实现
数据结构·c++·哈希算法·散列表
2501_9269783342 分钟前
人机通信协议--人和机器之间的交互想象
人工智能·经验分享·算法·ai写作
行者全栈架构师1 小时前
【鸿蒙心迹】互动卡片全链路——把核心功能放到桌面(FormKit 实战)(HarmonyOS 7.x)
前端·算法·架构
无定义_1 小时前
10.11日常训练
算法
Code_Solitude1 小时前
c语言:关于qsoet函数知识点
c语言·数据结构·算法
Nil2081 小时前
leetcode 49字母异位分组
算法·leetcode·哈希算法