【LeetCode】937、重新排列日志文件

937、Reorder Log Files重新排列日志文件

难度:简单

题目描述

  • 英文:

    You have an array of logs. Each log is a space delimited string of words.

    For each log, the first word in each log is an alphanumeric identifier. Then, either:

    • Each word after the identifier will consist only of lowercase letters, or;
    • Each word after the identifier will consist only of digits.

    We will call these two varieties of logs letter-logs and digit-logs. It is guaranteed that each log has at least one word after its identifier.

    Reorder the logs so that all of the letter-logs come before any digit-log. The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties. The digit-logs should be put in their original order.

    Return the final order of the logs.

  • 中文:

    你有一个日志数组 logs。每条日志都是以空格分隔的字串。

    对于每条日志,其第一个字为字母数字标识符。然后,要么:

    • 标识符后面的每个字将仅由小写字母组成,或;
    • 标识符后面的每个字将仅由数字组成。

    我们将这两种日志分别称为字母日志和数字日志。保证每个日志在其标识符后面至少有一个字。

    将日志重新排序,使得所有字母日志都排在数字日志之前。字母日志按字母顺序排序,忽略标识符,标识符仅用于表示关系。数字日志应该按原来的顺序排列。

    返回日志的最终顺序。

提示

  1. 0 <= logs.length <= 100
  2. 3 <= logs[i].length <= 100
  3. logs[i] is guaranteed to have an identifier, and a word after the identifier.

示例

Example 1:

1
2
Input: ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]

解题思路

思路一

先区分数字日志和字母日志,然后字母日志按内容排序,最后合并两部分内容输出。

代码提交

Python2,用时48ms,内存11.1M

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def reorderLogFiles(self, logs):
"""
:type logs: List[str]
:rtype: List[str]
"""
letterList = []
numberList = []
for log in logs:
logList = log.split(" ")
if logList[1].isdigit():
numberList.append(log)
else:
letterList.append((logList[0], " ".join(logList[1:])))
letterList.sort(key=lambda x:x[1])
resultList = [" ".join(a) for a in letterList]
return resultList+numberList

后来看了一下用时短的代码,方法都很简单,但是代码很简洁高效。

用0、1标记字母、数字日志,之后一次排序返回。

Python2,用时36ms,内存11.1M

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def reorderLogFiles(self, logs):
"""
:type logs: List[str]
:rtype: List[str]
"""
def f(log):
id, rest = log.split(' ', 1)
return (0, rest) if rest[0].isalpha() else (1,)

return sorted(logs, key = f)
-------------本文结束感谢您的阅读-------------
0%