Question

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorder-data-in-log-files/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Ideas
1、Answer( Java )
解法思路:简单自定义排序
Code
/**
* @author Listen 1024
* @description 937. 重新排列日志文件 (简单模拟排序题)
* 时间复杂度 O(nlogn)
* 空间复杂度 O(n)
* @date 2022-05-03 12:04
*/
class Solution {
public String[] reorderLogFiles(String[] logs) {
String[] res = new String[logs.length];
ArrayList<String> listNumDig = new ArrayList<>();
ArrayList<String> listStrDig = new ArrayList<>();
for (String log : logs) {
String[] strings = log.split("\\s+");
int i = strings[1].charAt(0);
if (i >= 48 && i <= 57) {//judge the num from [0,9] of the ASCII
listNumDig.add(log);
} else {
listStrDig.add(log);
}
}
listStrDig.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int index1 = o1.indexOf(" ");
int index2 = o2.indexOf(" ");
String temp1 = o1.substring(index1, o1.length());
String temp2 = o2.substring(index2, o2.length());
if (!temp1.equals(temp2)) {
return temp1.compareTo(temp2);
} else {
return o1.substring(0, index1).compareTo(o2.substring(0, index2));
}
}
});
int index = 0;
for (int i = 0; i < listStrDig.size(); i++) {
res[i] = listStrDig.get(i);
index++;
}
for (int i = 0; i < listNumDig.size(); i++) {
res[index] = listNumDig.get(i);
index++;
}
return res;
}
}
该博客详细介绍了如何解决LeetCode上的第937题——重新排列日志文件。作者提供了Java代码实现,通过自定义排序算法将包含数字的日志条目和纯字母的日志条目分别排序,最终合并成所需的排列顺序。时间复杂度为O(nlogn),空间复杂度为O(n)。

被折叠的 条评论
为什么被折叠?



