Link : https://leetcode.com/problems/reorder-data-in-log-files/
Problem :
You are given an array of logs
. Each log is a space-delimited string of words, where the first word is the identifier.
There are two types of logs:
- Letter-logs: All words (except the identifier) consist of lowercase English letters.
- Digit-logs: All words (except the identifier) consist of digits.
Reorder these logs so that:
- The letter-logs come before all digit-logs.
- The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
- The digit-logs maintain their relative ordering.
Return the final order of the logs.
Thoughts :
0. 分兩個 array 存。一個存 letter、一個存數字
1. 確認當前的 log 是 letter 還是數字。
2. 如果是 letter 存到 letter 陣列,如果是非 letter 存到nums陣列。
3. letter 的 array 做 sort、nums的按照原本的排序就好。
Solution :
class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
letters = []
nums = []
for log in logs:
logsplit = log.split(" ")
#print(logsplit[1])
if logsplit[1].isalpha():
letters.append((" ".join(logsplit[1:]), logsplit[0]))
#print(letters)
else:
nums.append(log)
letters.sort()
return [letter[1]+" "+letter[0] for letter in letters] + nums
time complexity = O(nlog n), space complexity = O(n)