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

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

解决方案

自定义排序

思路

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

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

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

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

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

定义比较函数 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;
    }
};
相关推荐
phltxy8 小时前
C语言操作符详解
java·c语言·算法
aqiu1111119 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye10 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考10 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
玖玥拾11 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研12 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
a1879272183113 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_9622974813 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye13 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展